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