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