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