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