]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
when viewing a selection list, show a link to the related lineitem PO if necessary
[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     /**
159      * Inserts a single lineitem into the growing table of lineitems
160      * @param {Object} li The lineitem object to insert
161      */
162     this.addLineitem = function(li) {
163         this.liCache[li.id()] = li;
164
165         // sort the lineitem notes on edit_time
166         if(!li.lineitem_notes()) li.lineitem_notes([]);
167
168         var liWrapper = new openils.acq.Lineitem({lineitem:li});
169         var row = self.rowTemplate.cloneNode(true);
170         row.setAttribute('li', li.id());
171         var tds = dojo.query('[attr]', row);
172         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
173         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
174
175         var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
176         if(isbn) {
177             // XXX media prefix for added content
178             dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
179         }
180
181         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
182         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
183         dojo.query('[name=notes_count]', row)[0].innerHTML = li.lineitem_notes().length;
184         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
185
186         if(li.purchase_order() && !this.isPO) {
187             openils.Util.show(nodeByName('po', row), 'inline');
188             nodeByName('po_link', row).setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
189         }
190
191         var countNode = nodeByName('count', row);
192         countNode.innerHTML = li.item_count() || 0;
193         countNode.id = 'acq-lit-copy-count-label-' + li.id();
194
195         // lineitem state
196         nodeByName('li_state', row).innerHTML = li.state(); // TODO i18n state labels
197
198         // lineitem price
199         var priceInput = dojo.query('[name=price]', row)[0];
200         var priceData = liWrapper.getPrice();
201         priceInput.value = (priceData) ? priceData.price : '';
202         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
203
204         var recv_link = dojo.query('[name=receive_link]', row)[0];
205
206         if(li.state() == 'on-order') {
207             recv_link.onclick = function() {
208                 self.receiveLi(li);
209                 openils.Util.hide(recv_link)
210             }
211         } else {
212             openils.Util.hide(recv_link);
213         }
214
215         // TODO we should allow editing before receipt, in which case the
216         // test should be "if 1 or more real (acp) copies exist
217         if(li.state() == 'received') {
218             var real_copies_link = dojo.query('[name=real_copies_link]', row)[0];
219             openils.Util.show(real_copies_link);
220             real_copies_link.onclick = function() {
221                 self.showRealCopies(li);
222             }
223         }
224
225         self.tbody.appendChild(row);
226         self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
227     };
228
229     /**
230      * Draws and shows the lineitem notes pane
231      */
232     this.drawLiNotes = function(li) {
233         var self = this;
234
235         li.lineitem_notes(
236             li.lineitem_notes().sort(
237                 function(a, b) { 
238                     if(a.edit_time() < b.edit_time()) return 1;
239                     return -1;
240                 }
241             )
242         );
243
244         while(this.liNotesTbody.childNodes[0])
245             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
246         this.show('notes');
247
248         acqLitCreateLiNoteSubmit.onClick = function() {
249             var value = acqLitCreateNoteText.attr('value');
250             if(!value) return;
251             var note = new fieldmapper.acqlin();
252             note.isnew(true);
253             note.value(value);
254             note.lineitem(li.id());
255             self.updateLiNotes(li, note);
256         }
257
258         dojo.byId('acq-lit-notes-save-button').onclick = function() {
259             self.updateLiNotes(li);
260         }
261
262         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
263     }
264
265     /**
266      * Draws a single lineitem note in the notes pane
267      */
268     this.addLiNote = function(li, note) {
269         if(note.isdeleted()) return;
270         var self = this;
271         var row = self.liNotesRow.cloneNode(true);
272         dojo.query('[name=value]', row)[0].innerHTML = note.value();
273
274         dojo.query('[name=delete]', row)[0].onclick = function() {
275             note.isdeleted(true);
276             self.liNotesTbody.removeChild(row);
277         };
278
279         if(note.edit_time()) {
280             dojo.query('[name=edit_time]', row)[0].innerHTML = 
281                 dojo.date.locale.format(
282                     dojo.date.stamp.fromISOString(note.edit_time()), 
283                     {formatLength:'short'});
284         }
285
286         self.liNotesTbody.appendChild(row);
287     }
288
289     /**
290      * Updates any new/changed/deleted notes on the server
291      */
292     this.updateLiNotes = function(li, newNote) {
293
294         var notes;
295         if(newNote) {
296             notes = [newNote];
297         } else {
298             notes = li.lineitem_notes().filter(
299                 function(note) {
300                     if(note.ischanged() || note.isnew() || note.isdeleted())
301                         return note;
302                 }
303             );
304         }
305
306         if(notes.length == 0) return;
307         progressDialog.show();
308
309         fieldmapper.standardRequest(
310             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
311             {   async : true,
312                 params : [this.authtoken, notes],
313                 onresponse : function(r) {
314                     var resp = openils.Util.readResponse(r);
315
316                     if(resp.complete) {
317
318                         if(!newNote) {
319                             // remove the old changed notes
320                             var list = [];
321                             dojo.forEach(li.lineitem_notes(), 
322                                 function(note) {
323                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
324                                         list.push(note);
325                                 }
326                             );
327                             li.lineitem_notes(list);
328                         }
329
330                         progressDialog.hide();
331                         self.drawLiNotes(li);
332                         return;
333                     }
334
335                     progressDialog.update(resp);
336                     var newnote = resp.note;
337
338                     if(!newnote.isdeleted()) {
339                         newnote.isnew(false);
340                         newnote.ischanged(false);
341                         li.lineitem_notes().push(newnote);
342                     }
343                 },
344             }
345         );
346     }
347
348     this.updateLiPrice = function(input, li) {
349
350         var price = input.value;
351         var liWrapper = new openils.acq.Lineitem({lineitem:li});
352         var oldPrice = liWrapper.getPrice() || null;
353
354         if(oldPrice) oldPrice = oldPrice.price;
355         if(price == oldPrice) return;
356
357         fieldmapper.standardRequest(
358             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
359             {   async : true,
360                 params : [this.authtoken, li.id(), price],
361                 oncomplete : function(r) {
362                     openils.Util.readResponse(r);
363                 }
364             }
365         );
366     }
367
368     this.removeLineitem = function(liId) {
369         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
370         delete this.liCache[liId];
371         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
372     }
373
374     this.drawInfo = function(liId) {
375         this.show('info');
376         openils.acq.Lineitem.fetchAttrDefs(
377             function() { 
378                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
379             } 
380         );
381     };
382
383     this._fetchLineitem = function(liId, handler) {
384
385         var li = this.liCache[liId];
386         if(li && li.marc() && li.lineitem_details())
387             return handler(li);
388         
389         fieldmapper.standardRequest(
390             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
391             {   async: true,
392
393                 params: [self.authtoken, liId, {
394                     flesh_attrs: true,
395                     flesh_li_details: true,
396                     flesh_fund_debit: true }],
397
398                 oncomplete: function(r) {
399                     var li = openils.Util.readResponse(r);
400                     handler(li)
401                 }
402             }
403         );
404     };
405
406     this._drawInfo = function(li) {
407
408         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
409
410         if(li.eg_bib_id()) {
411             openils.Util.hide('acq-lit-marc-order-record-label');
412             openils.Util.hide(acqLitEditOrderMarc.domNode);
413             openils.Util.show('acq-lit-marc-real-record-label');
414         } else {
415             openils.Util.show('acq-lit-marc-order-record-label');
416             openils.Util.show(acqLitEditOrderMarc.domNode);
417             openils.Util.hide('acq-lit-marc-real-record-label');
418         }
419
420         this.drawMarcHTML(li);
421         this.infoTbody = dojo.byId('acq-lit-info-tbody');
422
423         if(!this.infoRow)
424             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
425         while(this.infoTbody.childNodes[0])
426             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
427
428         for(var i = 0; i < li.attributes().length; i++) {
429             var attr = li.attributes()[i];
430             var row = this.infoRow.cloneNode(true);
431
432             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
433             var name = openils.acq.Lineitem.attrDefs[type].filter(
434                 function(a) {
435                     return (a.code() == attr.attr_name());
436                 }
437             ).pop().description();
438
439             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
440             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
441             this.infoTbody.appendChild(row);
442         }
443
444         if(li.eg_bib_id()) {
445             openils.Util.show('acq-lit-info-cat-link');
446             var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
447
448             if(openils.XUL.isXUL()) {
449
450                 var makeRecTab = function() {
451                                     xulG.new_tab(
452                         XUL_OPAC_WRAPPER,
453                                             {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
454                                             {
455                             no_xulG : false, 
456                             show_nav_buttons : true, 
457                             show_print_button : true, 
458                             opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + li.eg_bib_id())
459                         }
460                     );
461                 }
462                 link.setAttribute('href', 'javascript:void(0);');
463                 link.onclick = makeRecTab;
464
465             } else {
466                 var href = link.getAttribute('href');
467                 if(href.match(/=$/))
468                     link.setAttribute('href',  href + li.eg_bib_id());
469             }
470         } else {
471             openils.Util.hide('acq-lit-info-cat-link');
472         }
473     };
474
475     this.drawMarcHTML = function(li) {
476         var params = [null, true, li.marc()];
477         if(li.eg_bib_id()) 
478             params = [li.eg_bib_id(), true];
479
480         fieldmapper.standardRequest(
481             ['open-ils.search', 'open-ils.search.biblio.record.html'],
482             {   async: true,
483                 params: params,
484                 oncomplete: function(r) {
485                     dojo.byId('acq-lit-marc-div').innerHTML = 
486                         openils.Util.readResponse(r);
487                 }
488             }
489         );
490     }
491
492     this.drawCopies = function(liId) {
493         this.show('copies');
494         var self = this;
495         this.copyCache = {};
496         this.copyWidgetCache = {};
497
498         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
499         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
500         acqLitCopyCountInput.attr('value', '0');
501
502         while(this.copyTbody.childNodes[0])
503             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
504
505         this._drawBatchCopyWidgets();
506
507         this._fetchDistribFormulas(
508             function() {
509                 self._addDistribFormulaRow();
510                 openils.acq.Lineitem.fetchAttrDefs(
511                     function() { 
512                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}); 
513                     } 
514                 );
515             }
516         );
517     };
518
519     /**
520      * Insert a new row into the distribution formula selection form
521      */
522     this._addDistribFormulaRow = function() {
523         var self = this;
524
525         if(!self.distribFormulaStore) {
526             // no formulas, hide the form
527             openils.Util.hide('acq-lit-distrib-formula-tbody');
528             return;
529         }
530
531         if(!this.distribFormulaTemplate) 
532             this.distribFormulaTemplate = 
533                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
534
535         var row = dojo.byId('acq-lit-distrib-formula-tbody').appendChild(this.distribFormulaTemplate.cloneNode(true));
536
537         var selector = new dijit.form.FilteringSelect(
538             {store : self.distribFormulaStore}, 
539             nodeByName('selector', row)
540         );
541
542         var apply = new dijit.form.Button(
543             {label : 'Apply'},  // TODO i18n
544             nodeByName('set_button', row)
545         ); 
546
547         var release = new dijit.form.Button(
548             {label : 'Release', disabled: true}, // TODO i18n
549             nodeByName('rel_button', row)  
550         );
551
552         dojo.connect(apply, 'onClick', 
553             function() {
554                 var form_id = selector.attr('value');
555                 if(!form_id) return;
556                 apply.attr('disabled', true);
557                 release.attr('disabled', false);
558                 self._applyDistribFormula(form_id);
559             }
560         );
561
562         dojo.connect(release, 'onClick', 
563             function() {
564                 apply.attr('disabled', false);
565                 release.attr('disabled', true);
566             }
567         );
568     };
569
570     /**
571      * Applies a distrib formula to the current set of copies
572      */
573     this._applyDistribFormula = function(formula) {
574         if(!formula) return;
575
576         formula = this.distribForms.filter(
577             function(form) {
578                 return form.id() == formula;
579             }
580         )[0];
581
582         var copyRows = dojo.query('tr', self.copyTbody);
583
584         for(var rowIndex = 0; rowIndex < copyRows.length; rowIndex++) {
585             
586             var row = copyRows[rowIndex];
587             var copy_id = row.getAttribute('copy_id');
588             var copyWidgets = this.copyWidgetCache[copy_id];
589             var entryIndex = 0;
590             var entry = null;
591
592             // find the correct entry for the current row
593             dojo.forEach(formula.entries(), 
594                 function(e) {
595                     if(!entry) {
596                         entryIndex += e.item_count();
597                         if(entryIndex > rowIndex)
598                             entry = e;
599                     }
600                 }
601             );
602
603             if(entry) {
604                 
605                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
606                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
607     
608                 dojo.forEach(
609                     ['owning_lib', 'location'], 
610                     function(field) {
611                         if(entry[field]()) 
612                             copyWidgets[field].attr('value', (entry[field]()));
613                     }
614                 );
615             }
616         }
617     };
618
619     this._fetchDistribFormulas = function(onload) {
620         if(this.distribForms) {
621             onload();
622         } else {
623             var self = this;
624             fieldmapper.standardRequest(
625                 ['open-ils.acq', 'open-ils.acq.distribution_formula.ranged.retrieve.atomic'],
626                 {   async: true,
627                     params: [openils.User.authtoken],
628                     oncomplete: function(r) {
629                         self.distribForms = openils.Util.readResponse(r);
630                         if(!self.distribForms || self.distribForms.length == 0) {
631                             self.distribForms  = [];
632                             return onload();
633                         }
634                         self.distribFormulaStore = 
635                             new dojo.data.ItemFileReadStore(
636                                 {data:acqdf.toStoreData(self.distribForms)});
637                         onload();
638                     }
639                 }
640             );
641         }
642     }
643
644     this._drawBatchCopyWidgets = function() {
645         var row = this.copyBatchRow;
646         dojo.forEach(liDetailBatchFields, 
647             function(field) {
648                 if(self.copyBatchRowDrawn) {
649                     self.copyBatchWidgets[field].attr('value', null);
650                 } else {
651                     var widget = new openils.widget.AutoFieldWidget({
652                         fmField : field,
653                         fmClass : 'acqlid',
654                         parentNode : dojo.query('[name='+field+']', row)[0],
655                         orgLimitPerms : ['CREATE_PICKLIST'],
656                         dijitArgs : {required:false},
657                         forceSync : true
658                     });
659                     widget.build(
660                         function(w, ww) {
661                             self.copyBatchWidgets[field] = w;
662                         }
663                     );
664                 }
665             }
666         );
667         this.copyBatchRowDrawn = true;
668     };
669
670     this.batchCopyUpdate = function() {
671         var self = this;
672         for(var k in this.copyWidgetCache) {
673             var cache = this.copyWidgetCache[k];
674             dojo.forEach(liDetailBatchFields, function(f) {
675                 var newval = self.copyBatchWidgets[f].attr('value');
676                 if(newval) cache[f].attr('value', newval);
677             });
678         }
679     };
680
681     this._drawCopies = function(li) {
682         var self = this;
683
684         // this button sets the total number of copies for a given lineitem
685         acqLitAddCopyCount.onClick = function() { 
686             var count = acqLitCopyCountInput.attr('value');
687
688             // add new rows
689             while(self.copyCount() < count)
690                 self.addCopy(li); 
691             
692             // delete rows if necessary
693             var diff = self.copyCount() - count;
694             if(diff > 0) {
695                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
696                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
697                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
698                 } else {
699                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
700                 }
701             }
702         }
703
704
705         if(li.lineitem_details().length > 0) {
706             dojo.forEach(li.lineitem_details(),
707                 function(copy) {
708                     self.addCopy(li, copy);
709                 }
710             );
711         } else {
712             self.addCopy(li);
713         }
714     };
715
716     this.copyCount = function() {
717         var count = 0;
718         for(var id in this.copyCache) {
719             if(!this.copyCache[id].isdeleted())
720                 count++;
721         }
722         return count;
723     }
724
725     this.virtCopyId = -1;
726     this.addCopy = function(li, copy) {
727         var row = this.copyRow.cloneNode(true);
728         this.copyTbody.appendChild(row);
729         var self = this;
730
731         if(!copy) {
732             copy = new fieldmapper.acqlid();
733             copy.isnew(true);
734             copy.id(this.virtCopyId--);
735             copy.lineitem(li.id());
736         }
737
738         this.copyCache[copy.id()] = copy;
739         row.setAttribute('copy_id', copy.id());
740         self.copyWidgetCache[copy.id()] = {};
741
742         acqLitCopyCountInput.attr('value', self.copyCount()+'');
743
744         dojo.forEach(liDetailFields,
745             function(field) {
746                 var widget = new openils.widget.AutoFieldWidget({
747                     fmObject : copy,
748                     fmField : field,
749                     fmClass : 'acqlid',
750                     parentNode : dojo.query('[name='+field+']', row)[0],
751                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
752                     readOnly : Boolean(copy.eg_copy_id())
753                 });
754                 widget.build(
755                     // make sure we capture the value from any async widgets
756                     function(w, ww) { 
757                         copy[field](ww.getFormattedValue()) 
758                         self.copyWidgetCache[copy.id()][field] = w;
759                     }
760                 );
761                 dojo.connect(widget.widget, 'onChange', 
762                     function(val) { 
763                         if(copy.isnew() || val != copy[field]()) {
764                             // prevent setting ischanged() automatically on widget load for existing copies
765                             copy[field](widget.getFormattedValue()) 
766                             copy.ischanged(true);
767                         }
768                     }
769                 );
770             }
771         );
772
773         var recv_link = dojo.query('[name=receive]', row)[0];
774         if(copy.recv_time()) {
775             openils.Util.hide(recv_link);
776         } else {
777             recv_link.onclick = function() {
778                 self.receiveLid(copy);
779                 openils.Util.hide(recv_link);
780             }
781         }
782
783         if(this.isPO) {
784             openils.Util.hide(dojo.query('[name=delete]', row)[0].parentNode);
785         } else {
786             dojo.query('[name=delete]', row)[0].onclick = 
787                 function() { self.deleteCopy(row) };
788         }
789     };
790
791     this.deleteCopy = function(row) {
792         var copy = this.copyCache[row.getAttribute('copy_id')];
793         copy.isdeleted(true);
794         if(copy.isnew())
795             delete this.copyCache[copy.id()];
796         this.copyTbody.removeChild(row);
797     }
798
799     this.saveCopyChanges = function(liId) {
800         var self = this;
801         var copies = [];
802
803
804         openils.Util.show('acq-lit-update-copies-progress');
805
806         var total = 0;
807         for(var id in this.copyCache) {
808             var c = this.copyCache[id];
809             if(!c.isdeleted()) total++;
810             if(c.isnew() || c.ischanged() || c.isdeleted()) {
811                 if(c.id() < 0) c.id(null);
812                 copies.push(c);
813             }
814         }
815
816         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
817
818         if(copies.length == 0)
819             return;
820
821         fieldmapper.standardRequest(
822             ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
823             {   async: true,
824                 params: [openils.User.authtoken, copies],
825                 onresponse: function(r) {
826                     var res = openils.Util.readResponse(r);
827                     litUpdateCopiesProgress.update(res);
828                 },
829                 oncomplete: function() {
830                     openils.Util.hide('acq-lit-update-copies-progress');
831                     self.drawCopies(liId); 
832                 }
833             }
834         );
835     }
836
837     this.applySelectedLiAction = function(action) {
838         var self = this;
839         switch(action) {
840
841             case 'delete_selected':
842                 this._deleteLiList(self.getSelected());
843                 break;
844
845             case 'create_order':
846
847                 if(!this.createPoProviderSelector) {
848                     var widget = new openils.widget.AutoFieldWidget({
849                         fmField : 'provider',
850                         fmClass : 'acqpo',
851                         parentNode : dojo.byId('acq-lit-po-provider'),
852                     });
853                     widget.build(
854                         function(w) { self.createPoProviderSelector = w; }
855                     );
856                 }
857
858                 if(!this.createPoAgencySelector) {
859                     var widget = new openils.widget.AutoFieldWidget({
860                         fmField : 'ordering_agency',
861                         fmClass : 'acqpo',
862                         parentNode : dojo.byId('acq-lit-po-agency'),
863                         orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
864                     });
865                     widget.build(
866                         function(w) { self.createPoAgencySelector = w; }
867                     );
868                 }
869
870          
871                 acqLitPoCreateDialog.show();
872                 break;
873
874             case 'save_picklist':
875                 this._loadPLSelect();
876                 acqLitSavePlDialog.show();
877                 break;
878
879             case 'print_po':
880                 this.printPO();
881                 break;
882
883             case 'receive_po':
884                 this.receivePO();
885                 break;
886
887             case 'rollback_receive_po':
888                 this.rollbackPoReceive();
889                 break;
890
891             case 'create_assets':
892                 this.createAssets();
893                 break;
894
895             case 'add_brief_record':
896                 if(this.isPO)
897                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
898                 else
899                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
900         }
901     }
902
903     this.createAssets = function() {
904         if(!this.isPO) return;
905         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
906         this.show('acq-lit-progress-numbers');
907         var self = this;
908         fieldmapper.standardRequest(
909             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
910             {   async: true,
911                 params: [this.authtoken, this.isPO],
912                 onresponse: function(r) {
913                     var resp = openils.Util.readResponse(r);
914                     self._updateProgressNumbers(resp, true);
915                 }
916             }
917         );
918     }
919
920     this.printPO = function() {
921         if(!this.isPO) return;
922         progressDialog.show(true);
923         fieldmapper.standardRequest(
924             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
925             {   async: true,
926                 params: [this.authtoken, this.isPO, 'html'],
927                 oncomplete: function(r) {
928                     progressDialog.hide();
929                     var evt = openils.Util.readResponse(r);
930                     if(evt && evt.template_output()) {
931                         win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
932                         win.document.body.innerHTML = evt.template_output().data();
933                     }
934                 }
935             }
936         );
937     }
938
939
940     this.receivePO = function() {
941         if(!this.isPO) return;
942         this.show('acq-lit-progress-numbers');
943         var self = this;
944         fieldmapper.standardRequest(
945             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
946             {   async: true,
947                 params: [this.authtoken, this.isPO],
948                 onresponse : function(r) {
949                     var resp = openils.Util.readResponse(r);
950                     self._updateProgressNumbers(resp, true);
951                 },
952             }
953         );
954     }
955
956     this.receiveLi = function(li) {
957         if(!this.isPO) return;
958         progressDialog.show(true);
959         fieldmapper.standardRequest(
960             ['open-ils.acq', 'open-ils.acq.lineitem.receive'],
961             {   async: true,
962                 params: [this.authtoken, li.id()],
963                 onresponse : function(r) {
964                     var resp = openils.Util.readResponse(r);
965                     progressDialog.hide();
966                 },
967             }
968         );
969     }
970
971     this.receiveLid = function(li) {
972         if(!this.isPO) return;
973         progressDialog.show(true);
974         fieldmapper.standardRequest(
975             ['open-ils.acq', 'open-ils.acq.lineitem_detail.receive'],
976             {   async: true,
977                 params: [this.authtoken, li.id()],
978                 onresponse : function(r) {
979                     var resp = openils.Util.readResponse(r);
980                     progressDialog.hide();
981                 },
982             }
983         );
984     }
985
986     this.rollbackPoReceive = function() {
987         if(!this.isPO) return;
988         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
989         this.show('acq-lit-progress-numbers');
990         var self = this;
991         fieldmapper.standardRequest(
992             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
993             {   async: true,
994                 params: [this.authtoken, this.isPO],
995                 onresponse : function(r) {
996                     var resp = openils.Util.readResponse(r);
997                     self._updateProgressNumbers(resp, true);
998                 },
999             }
1000         );
1001     }
1002
1003     this._updateProgressNumbers = function(resp, reloadOnComplete) {
1004         if(!resp) return;
1005         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1006         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1007         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1008         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1009         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1010         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1011         if(resp.complete && reloadOnComplete) 
1012             location.href = location.href;
1013     }
1014
1015
1016     this._createPO = function(fields) {
1017         this.show('acq-lit-progress-numbers');
1018         var po = new fieldmapper.acqpo();
1019         po.provider(this.createPoProviderSelector.attr('value'));
1020         po.ordering_agency(this.createPoAgencySelector.attr('value'));
1021
1022         var selected = this.getSelected( (fields.create_from == 'all') );
1023         if(selected.length == 0) return;
1024
1025         var max = selected.length * 3;
1026
1027         var self = this;
1028         fieldmapper.standardRequest(
1029             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1030             {   async: true,
1031                 params: [
1032                     openils.User.authtoken, 
1033                     po, 
1034                     {
1035                         lineitems : selected.map(function(li) { return li.id() }),
1036                         create_assets : fields.create_assets[0],
1037                     }
1038                 ],
1039
1040                 onresponse : function(r) {
1041                     var resp = openils.Util.readResponse(r);
1042                     self._updateProgressNumbers(resp);
1043                     if(resp.complete) 
1044                         location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1045                 }
1046             }
1047         );
1048     }
1049
1050     this._deleteLiList = function(list, idx) {
1051         if(idx == null) idx = 0;
1052         if(idx >= list.length) return;
1053         var liId = list[idx].id();
1054         fieldmapper.standardRequest(
1055             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1056             {   async: true,
1057                 params: [openils.User.authtoken, liId],
1058                 oncomplete: function(r) {
1059                     self.removeLineitem(liId);
1060                     self._deleteLiList(list, ++idx);
1061                 }
1062             }
1063         );
1064     }
1065
1066     this.editOrderMarc = function(li) {
1067
1068         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
1069             to true in about:config */
1070
1071         if(!openils.XUL.enableXPConnect()) return;
1072
1073         if(openils.XUL.isXUL()) {
1074             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1075         } else {
1076
1077             win = window.open('/xul/server/cat/marcedit.xul'); 
1078             var self = this;
1079             win.xulG = {
1080                 record : {marc : li.marc()},
1081                 save : {
1082                     label: 'Save Record', // XXX I18N
1083                     func: function(xmlString) {
1084                         li.marc(xmlString);
1085                         fieldmapper.standardRequest(
1086                             ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1087                             {   async: true,
1088                                 params: [openils.User.authtoken, li],
1089                                 oncomplete: function(r) {
1090                                     openils.Util.readResponse(r);
1091                                     win.close();
1092                                     self.drawInfo(li.id())
1093                                 }
1094                             }
1095                         );
1096                     },
1097                 }
1098             };
1099         }
1100     }
1101
1102     this._savePl = function(values) {
1103         var self = this;
1104         var selected = this.getSelected( (values.which == 'all') );
1105         openils.Util.show('acq-lit-generic-progress');
1106
1107         if(values.new_name) {
1108             openils.acq.Picklist.create(
1109                 {name: values.new_name}, 
1110                 function(id) {
1111                     self._updateLiList(id, selected, 0, 
1112                         function(){
1113                             location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1114                         });
1115                 }
1116             );
1117         } else if(values.existing_pl) {
1118             // update lineitems to use an existing picklist
1119             self._updateLiList(values.existing_pl, selected, 0, 
1120                 function(){
1121                     location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1122                 });
1123         }
1124     }
1125
1126     this._updateLiList = function(pl, list, idx, oncomplete) {
1127         if(idx >= list.length) return oncomplete();
1128         var li = list[idx];
1129         li.picklist(pl);
1130         litGenericProgress.update({maximum: list.length, progress: idx});
1131         new openils.acq.Lineitem({lineitem:li}).update(
1132             function(r) {
1133                 self._updateLiList(pl, list, ++idx, oncomplete);
1134             }
1135         );
1136     }
1137
1138     this._loadPLSelect = function() {
1139         if(this._plSelectLoaded) return;
1140         var plList = [];
1141         function handleResponse(r) {
1142             plList.push(r.recv().content());
1143         }
1144         var method = 'open-ils.acq.picklist.user.retrieve';
1145         fieldmapper.standardRequest(
1146             ['open-ils.acq', method],
1147             {   async: true,
1148                 params: [this.authtoken],
1149                 onresponse: handleResponse,
1150                 oncomplete: function() {
1151                     self._plSelectLoaded = true;
1152                     acqLitAddExistingSelect.store = 
1153                         new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
1154                     acqLitAddExistingSelect.setValue();
1155                 }
1156             }
1157         );
1158     }
1159
1160     // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
1161     this.showRealCopies = function(li) {
1162         while(this.realCopiesTbody.childNodes[0])
1163             this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
1164         this.show('real-copies');
1165
1166         var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1167         this.realCopyList = [];
1168         this.volCache = {};
1169         var tabIndex = 1000;
1170         var self = this;
1171
1172         acqLitSaveRealCopies.onClick = function() {
1173             self.saveRealCopies();
1174         }
1175
1176         this._fetchLineitem(li.id(), 
1177             function(fullLi) {
1178                 li = self.liCache[li.id()] = fullLi;
1179
1180                 pcrud.search(
1181                     'acp', {
1182                         id : li.lineitem_details().map(
1183                             function(item) { return item.eg_copy_id() }
1184                         )
1185                     }, {
1186                         async : true,
1187                         streaming : true,
1188                         onresponse : function(r) {
1189                             var copy = openils.Util.readResponse(r);
1190                             var volId = copy.call_number();
1191                             var volume = self.volCache[volId];
1192                             if(!volume) {
1193                                 volume = self.volCache[volId] = pcrud.retrieve('acn', volId);
1194                             }
1195                             self.addRealCopy(volume, copy, tabIndex++);
1196                         }
1197                     }
1198                 );
1199             }
1200         );
1201     }
1202
1203     this.addRealCopy = function(volume, copy, tabIndex) {
1204         var row = this.realCopiesRow.cloneNode(true);
1205         this.realCopyList.push(copy);
1206
1207         var selectNode;
1208         dojo.forEach(
1209             ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
1210
1211             function(field) {
1212                 var isvol = (field == 'owning_lib' || field == 'label');
1213                 var widget = new openils.widget.AutoFieldWidget({
1214                     fmField : field,
1215                     fmObject : isvol ? volume : copy,
1216                     parentNode : nodeByName(field, row),
1217                     readOnly : (field != 'barcode'),
1218                 });
1219
1220                 var widgetDrawn = null;
1221
1222                 if(field == 'barcode') {
1223
1224                     widgetDrawn = function(w, ww) {
1225                         var node = w.domNode;
1226                         node.setAttribute('tabindex', ''+tabIndex);
1227
1228                         // on enter, select the next barcode input
1229                         dojo.connect(w, 'onKeyDown',
1230                             function(e) {
1231                                 if(e.keyCode == dojo.keys.ENTER) {
1232                                     var ti = node.getAttribute('tabindex');
1233                                     var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
1234                                     if(nextNode) nextNode.select();
1235                                 }
1236                             }
1237                         );
1238
1239                         dojo.connect(w, 'onChange', 
1240                             function(val) { 
1241                                 if(!val || val == copy.barcode()) return;
1242                                 copy.ischanged(true);
1243                                 copy.barcode(val);
1244                             }
1245                         );
1246
1247
1248                         if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
1249                             selectNode = node;
1250                     }
1251                 }
1252
1253                 widget.build(widgetDrawn);
1254             }
1255         );
1256
1257         this.realCopiesTbody.appendChild(row);
1258         if(selectNode) selectNode.select();
1259     };
1260
1261     this.saveRealCopies = function() {
1262         var pcrud = new openils.PermaCrud({authtoken : this.authtoken});
1263         progressDialog.show(true);
1264         var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
1265         pcrud.update(list, {oncomplete: function() { 
1266             progressDialog.hide();
1267             self.show('list');
1268         }});
1269     }
1270 }
1271
1272
1273