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