]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
Acq: the XULTermLoader dijit now returns the first columns of CSV rows
[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.acq.Lineitem');
10 dojo.require('openils.acq.PO');
11 dojo.require('openils.acq.Picklist');
12 dojo.require('openils.widget.AutoFieldWidget');
13 dojo.require('dojo.data.ItemFileReadStore');
14 dojo.require('openils.widget.ProgressDialog');
15 dojo.require('openils.PermaCrud');
16
17 dojo.requireLocalization('openils.acq', 'acq');
18 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
19 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
20 var li_exportable_attrs = ["issn", "isbn", "upc"];
21
22 var fundLabelFormat = [
23     '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
24 ];
25 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
26
27 function nodeByName(name, context) {
28     return dojo.query('[name='+name+']', context)[0];
29 }
30
31
32 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
33 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
34 var fundStyles = {
35     "stop": "color: #c00; font-weight: bold;",
36     "warning": "color: #c93;"
37 };
38
39 function AcqLiTable() {
40
41     var self = this;
42     this.liCache = {};
43     this.plCache = {};
44     this.poCache = {};
45     this.relCache = {};
46     this.haveFundClass = {}
47     this.fundBalanceState = {};
48     this.realDfaCache = {};
49     this.virtDfaCounts = {};
50     this.virtDfaId = -1;
51     this.dfeOffset = 0;
52     this.claimEligibleLidByLi = {};
53     this.claimEligibleLid = {};
54     this.toggleState = false;
55     this.tbody = dojo.byId('acq-lit-tbody');
56     this.selectors = [];
57     this.noteAcks = {};
58     this.authtoken = openils.User.authtoken;
59     this.pcrud = new openils.PermaCrud();
60     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
61     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
62     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
63     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
64     this.copyBatchWidgets = {};
65     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
66     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
67     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
68     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
69     this._copy_fields_for_acqdf = ['owning_lib', 'location'];
70     this.invoiceLinkDialogManager = new InvoiceLinkDialogManager("li");
71     this.claimDialog = new ClaimDialogManager(
72         liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
73         function(li) {    /* callback that fires when claims are made */
74             self.fetchClaimInfo(li.id(), /* force update */ true);
75         }
76     );
77
78     dojo.connect(acqLitLiActionsSelector, 'onChange', 
79         function() { 
80             self.applySelectedLiAction(this.attr('value')) 
81             acqLitLiActionsSelector.attr('value', '_');
82         });
83
84     acqLitCreatePoSubmit.onClick = function() {
85         if (self._confirmPoPrepaySituation()) {
86             acqLitPoCreateDialog.hide();
87             self._createPO(acqLitPoCreateDialog.getValues());
88         } else {
89             return false;
90         }
91     }
92
93     acqLitSavePlButton.onClick = function() {
94         acqLitSavePlDialog.hide();
95         self._savePl(acqLitSavePlDialog.getValues());
96     }
97
98     acqLitCancelLiStateButton.onClick = function() {
99         acqLitChangeLiStateDialog.hide();
100     }
101     acqLitSaveLiStateButton.onClick = function() {
102         acqLitChangeLiStateDialog.hide();
103         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
104     }
105
106
107     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
108     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
109     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
110     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
111     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
112
113     this.reset = function(keep_selectors) {
114         while(self.tbody.childNodes[0])
115             self.tbody.removeChild(self.tbody.childNodes[0]);
116         self.noteAcks = {};
117         self.relCache = {};
118
119         if (!keep_selectors)
120             self.selectors = [];
121     };
122     
123     this.setNext = function(handler) {
124         var link = dojo.byId('acq-lit-next');
125         if(handler) {
126             dojo.style(link, 'visibility', 'visible');
127             link.onclick = handler;
128         } else {
129             dojo.style(link, 'visibility', 'hidden');
130         }
131     };
132
133     this.setPrev = function(handler) {
134         var link = dojo.byId('acq-lit-prev');
135         if(handler) {
136             dojo.style(link, 'visibility', 'visible'); 
137             link.onclick = handler; 
138         } else {
139             dojo.style(link, 'visibility', 'hidden');
140         }
141     };
142
143     this.show = function(div) {
144         openils.Util.hide('acq-lit-table-div');
145         openils.Util.hide('acq-lit-info-div');
146         openils.Util.hide('acq-lit-li-details');
147         openils.Util.hide('acq-lit-notes-div');
148         openils.Util.hide('acq-lit-real-copies-div');
149         switch(div) {
150             case 'list':
151                 openils.Util.show('acq-lit-table-div');
152                 break;
153             case 'info':
154                 openils.Util.show('acq-lit-info-div');
155                 break;
156             case 'copies':
157                 openils.Util.show('acq-lit-li-details');
158                 break;
159             case 'real-copies':
160                 openils.Util.show('acq-lit-real-copies-div');
161                 break;
162             case 'notes':
163                 openils.Util.show('acq-lit-notes-div');
164                 break;
165             default:
166                 if(div) 
167                     openils.Util.show(div);
168         }
169     }
170
171     this.hide = function() {
172         this.show(null);
173     }
174
175     this.toggleSelect = function() {
176         if(self.toggleState) 
177             dojo.forEach(self.selectors, function(i){i.checked = false});
178         else 
179             dojo.forEach(self.selectors, function(i){i.checked = true});
180         self.toggleState = !self.toggleState;
181     };
182
183
184     /** @param all If true, assume all are selected */
185     this.getSelected = function(all) {
186         var selected = [];
187         var indices = {};   /* use to uniqify. needed in paging situations. */
188         dojo.forEach(self.selectors, 
189             function(i) { 
190                 if(i.checked || all)
191                     indices[i.parentNode.parentNode.getAttribute('li')] = true;
192             }
193         );
194         return openils.Util.objectProperties(indices).map(
195             function(liId) { return self.liCache[liId]; }
196         );
197     };
198
199     this.setRowAttr = function(td, liWrapper, field, type) {
200         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
201         td.appendChild(document.createTextNode(val));
202     };
203
204     this.setClaimPolicyControl = function(li, row) {
205         if (!self.claimPolicyPicker) {
206             self.claimPolicyPicker = true; /* prevents a race condition */
207             new openils.widget.AutoFieldWidget({
208                 "parentNode": "acq-lit-li-claim-policy",
209                 "fmClass": "acqclp",
210                 "selfReference": true,
211                 "dijitArgs": {"required": true}
212             }).build(function(w) { self.claimPolicyPicker = w; });
213         }
214
215         if (!row) row = this._findLiRow(li);
216
217         var actViewPolicy = nodeByName("action_view_claim_policy", row);
218         if (li.claim_policy())
219             actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
220
221         if (!actViewPolicy.onclick) {
222             actViewPolicy.onclick = function() {
223                 if (li.claim_policy())
224                     self.claimPolicyPicker.attr("value", li.claim_policy());
225                 liClaimPolicyDialog.show();
226                 liClaimPolicySave.onClick = function() {
227                     self.changeClaimPolicy(
228                         [li], self.claimPolicyPicker.attr("value"),
229                         function() {
230                             self.setClaimPolicyControl(li, row);
231                             liClaimPolicyDialog.hide();
232                         }
233                     );
234                 }
235             };
236         }
237     };
238
239     this.fetchClaimInfo = function(liId, force, callback, row) {
240         this._fetchLineitem(
241             liId, function(full) {
242                 self.liCache[full.id()] = full;
243                 self.checkClaimEligibility(full, callback, row);
244             }, force
245         );
246     }
247
248     /**
249      * Inserts a single lineitem into the growing table of lineitems
250      * @param {Object} li The lineitem object to insert
251      */
252     this.addLineitem = function(li, skip_final_placement) {
253         this.liCache[li.id()] = li;
254
255         // sort the lineitem notes on edit_time
256         if(!li.lineitem_notes()) li.lineitem_notes([]);
257
258         var liWrapper = new openils.acq.Lineitem({lineitem:li});
259         var row = self.rowTemplate.cloneNode(true);
260         row.setAttribute('li', li.id());
261         var tds = dojo.query('[attr]', row);
262         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
263         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
264
265         var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
266         if(isbn) {
267             // XXX media prefix for added content
268             dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
269         }
270
271         nodeByName("worksheet_link", row).href =
272             oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
273
274         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
275         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
276         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
277
278         this.fetchClaimInfo(li.id(), false, null, row);
279
280         this.updateLiNotesCount(li, row);
281
282         this.setClaimPolicyControl(li, row);
283
284         // show which PO this lineitem is a member of
285         if(li.purchase_order() && !this.isPO) {
286             var po = 
287                 this.poCache[li.purchase_order()] =
288                 this.poCache[li.purchase_order()] ||
289                 fieldmapper.standardRequest(
290                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
291                     {params: [
292                         this.authtoken, li.purchase_order(), {
293                             "flesh_price_summary": true,
294                             "flesh_lineitem_count": true
295                         }
296                     ]});
297             if(po && !this.isMeta) {
298                 openils.Util.show(nodeByName('po', row), 'inline');
299                 var link = nodeByName('po_link', row);
300                 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
301                 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
302             }
303         }
304
305         // show which picklist this lineitem is a member of
306         if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
307             var pl = 
308                 this.plCache[li.picklist()] = 
309                 this.plCache[li.picklist()] || 
310                 fieldmapper.standardRequest(
311                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
312                     {params: [this.authtoken, li.picklist()]});
313             if (pl) {
314                 if (pl.name() == "")
315                     openils.Util.show(nodeByName("bib_origin", row), "inline");
316
317                 openils.Util.show(nodeByName('pl', row), 'inline');
318                 var link = nodeByName('pl_link', row);
319                 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
320                 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
321             }
322         }
323
324         var countNode = nodeByName('count', row);
325         var count = li.item_count() || 0;
326         if (typeof(this._copy_count_cb) == "function") {
327             this._copy_count_cb(li.id(), count);
328         }
329         countNode.innerHTML = count;
330         countNode.id = 'acq-lit-copy-count-label-' + li.id();
331
332         // lineitem price
333         var priceInput = dojo.query('[name=price]', row)[0];
334         priceInput.value = li.estimated_unit_price() || '';
335         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
336
337         // show either "mark received" or "unreceive" as appropriate
338         this.updateLiState(li, row);
339
340         if (!skip_final_placement) {
341             self.tbody.appendChild(row);
342             self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
343         } else {
344             return row;
345         }
346     };
347
348     this._liCountClaims = function(li) {
349         var total = 0;
350         for (var i = 0; i < li.lineitem_details().length; i++)
351             total += li.lineitem_details()[i].claims().length;
352         return total;
353     };
354
355     this._findLiRow = function(li) {
356         return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
357     };
358
359     this.reconsiderClaimControl = function(li, row) {
360         var option = nodeByName("action_manage_claims", row);
361         var eligible = this.claimEligibleLidByLi[li.id()].length;
362         var count = this._liCountClaims(li);
363         if (!row) row = this._findLiRow(li);
364
365         option.disabled = !(count || eligible);
366         option.innerHTML =
367             dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
368         option.onclick = function() { self.claimDialog.show(li); };
369     };
370
371     this.clearEligibility = function(li) {
372         this.claimEligibleLidByLi[li.id()] = [];
373
374         if (li.lineitem_details()) {
375             li.lineitem_details().forEach(
376                 function(lid) { delete self.claimEligibleLid[lid.id()]; }
377             );
378         }
379
380         if (this.copyCache) {
381             var to_del = [];
382             for (var k in this.copyCache) {
383                 if (this.copyCache[k].lineitem() == li.id())
384                     to_del.push(k);
385             }
386             to_del.forEach(
387                 function(k) { delete self.claimEligibleLid[k]; }
388             );
389         }
390     };
391
392     this.checkClaimEligibility = function(li, callback, row) {
393         this.clearEligibility(li);
394         fieldmapper.standardRequest(
395             ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
396                 "params": [openils.User.authtoken, {"lineitem": li.id()}],
397                 "async": true,
398                 "onresponse": function(r) {
399                     if (r = openils.Util.readResponse(r)) {
400                         self.claimEligibleLidByLi[li.id()].push(
401                             r.lineitem_detail()
402                         );
403                         self.claimEligibleLid[r.lineitem_detail()] = true;
404                     }
405                 },
406                 "oncomplete": function() {
407                     self.reconsiderClaimControl(li, row);
408                     if (typeof(callback) == "function")
409                         callback();
410                 }
411             }
412         );
413     };
414
415     this.updateLiNotesCount = function(li, row) {
416         if (!row) row = this._findLiRow(li);
417
418         var has_notes = (li.lineitem_notes().filter(
419                 function(o) { return Boolean (o.alert_text()); }
420             ).length > 0);
421
422         /* U+2691 is the code point for a filled-in flag character */
423         nodeByName("notes_alert_flag", row).innerHTML =
424              has_notes ? "&#x2691;" : "";
425         nodeByName("noteslink", row).style.fontStyle =
426             has_notes ? "italic" : "normal";
427         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
428     };
429
430     /* XXX NOT related to _updateLiState(). rethink */
431     this.updateLiState = function(li, row) {
432         if (!row) row = this._findLiRow(li);
433
434         var actReceive = nodeByName("action_mark_recv", row);
435         var actUnRecv = nodeByName("action_mark_unrecv", row);
436         var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
437         var actHoldingsMaint = nodeByName("action_holdings_maint", row);
438
439         var actNewInvoice = nodeByName('action_new_invoice', row);
440         var actLinkInvoice = nodeByName('action_link_invoice', row);
441         var actViewInvoice = nodeByName('action_view_invoice', row);
442
443         nodeByName('action_view_history', row).onclick = 
444             function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
445
446         var state_cell = nodeByName("li_state", row);
447
448         if (li.state() == "cancelled") {
449             if (typeof li.cancel_reason() == "object") {
450                 var holds_state = dojo.create(
451                     "span", {
452                         "style": "border-bottom: 1px dashed #000;",
453                         "innerHTML": li.state()
454                     }, state_cell, "only"
455                 );
456                 new dijit.Tooltip(
457                     {
458                         "label": "<em>" + li.cancel_reason().label() +
459                             "</em><br />" + li.cancel_reason().description(),
460                         "connectId": [holds_state]
461                     }, dojo.create("span", null, state_cell, "last")
462                 );
463             } else {
464                 state_cell.innerHTML = li.state(); // TODO i18n state labels
465             }
466         } else {
467             state_cell.innerHTML = li.state(); // TODO i18n state labels
468         }
469
470
471         /* handle row coloring for based on LI state */
472         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
473         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
474
475         /* handle links that appear/disappear based on whether LI is received */
476         if (this.isPO) {
477             var self = this;
478
479             actNewInvoice.onclick = function() {
480                 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
481                 nodeByName("action_none", row).selected = true;
482             };
483             actLinkInvoice.onclick = function() {
484                 self.invoiceLinkDialogManager.target = li;
485                 acqLitLinkInvoiceDialog.show();
486                 nodeByName("action_none", row).selected = true;
487             };
488             actViewInvoice.onclick = function() {
489                 location.href = oilsBasePath +
490                     "/acq/search/unified?so=" +
491                     base64Encode({"jub":[{"id": li.id()}]}) +
492                     "&rt=invoice";
493                 nodeByName("action_none", row).selected = true;
494             };
495
496             actNewInvoice.disabled = false;
497             actLinkInvoice.disabled = false;
498             actViewInvoice.disabled = false;
499
500             switch(li.state()) {
501                 case "on-order":
502                     actReceive.disabled = false;
503                     actReceive.onclick = function() {
504                         if (self.checkLiAlerts(li.id()))
505                             self.issueReceive(li);
506                         nodeByName("action_none", row).selected = true;
507                     };
508                     return;
509
510                 case "received":
511                     actUnRecv.disabled = false;
512                     actUnRecv.onclick = function() {
513                         if (confirm(localeStrings.UNRECEIVE_LI))
514                             self.issueReceive(li, /* rollback */ true);
515                         nodeByName("action_none", row).selected = true;
516                     };
517                     // TODO we should allow editing before receipt, in which case the
518                     // test should be "if 1 or more real (acp) copies exist
519                     actUpdateBarcodes.disabled = false;
520                     actUpdateBarcodes.onclick = function() {
521                         self.showRealCopyEditUI(li);
522                         nodeByName("action_none", row).selected = true;
523                     }
524                     actHoldingsMaint.disabled = false;
525                     actHoldingsMaint.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
526
527                     return;
528             }
529         }
530     };
531
532
533     this._setAlertStore = function() {
534         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
535             {
536                 "data": acqliat.toStoreData(
537                     this.pcrud.search(
538                         "acqliat", {"id": {"!=": null}}
539                     )
540                 )
541             }
542         );
543         acqLitAlertAlertText.setValue(); /* make the store "live" */
544         acqLitAlertAlertText._store_ready = true;
545     };
546
547     /**
548      * Draws and shows the lineitem notes pane
549      */
550     this.drawLiNotes = function(li) {
551         var self = this;
552
553         if (!acqLitAlertAlertText._store_ready)
554             this._setAlertStore();
555
556         li.lineitem_notes(
557             li.lineitem_notes().sort(
558                 function(a, b) { 
559                     if(a.edit_time() < b.edit_time()) return 1;
560                     return -1;
561                 }
562             )
563         );
564
565         while(this.liNotesTbody.childNodes[0])
566             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
567         this.show('notes');
568
569         acqLitCreateNoteSubmit.onClick = function() {
570             var value = acqLitCreateNoteText.attr('value');
571             if(!value) return;
572             var note = new fieldmapper.acqlin();
573             note.isnew(true);
574             note.vendor_public(
575                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
576             );
577             note.value(value);
578             note.lineitem(li.id());
579
580             self.updateLiNotes(li, note);
581             acqLitCreateNoteVendorPublic.attr("checked", false);
582             acqLitCreateNoteText.attr("value", "");
583         }
584
585         acqLitCreateAlertSubmit.onClick = function() {
586             if (!acqLitAlertAlertText.item) {
587                 alert(localeStrings.ALERT_UNSELECTED);
588                 return;
589             }
590
591             var alert_text = new fieldmapper.acqliat().fromStoreItem(
592                 acqLitAlertAlertText.item
593             );
594             var value = acqLitAlertNoteValue.attr("value") || "";
595
596             var note = new fieldmapper.acqlin();
597             note.isnew(true);
598             note.lineitem(li.id());
599             note.value(value);
600             note.alert_text(alert_text);
601
602             self.updateLiNotes(li, note);
603         }
604
605         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
606     }
607
608     /**
609      * Draws a single lineitem note in the notes pane
610      */
611     this.addLiNote = function(li, note) {
612         if(note.isdeleted()) return;
613         var self = this;
614         var row = self.liNotesRow.cloneNode(true);
615         nodeByName("value", row).innerHTML = note.value();
616         var alert_node = nodeByName("alert_code", row);
617         if (note.alert_text()) {
618             alert_node.innerHTML = note.alert_text().code();
619             if (note.alert_text().description()) {
620                 new dijit.Tooltip(
621                     {
622                         "connectId": [alert_node],
623                         "label": note.alert_text().description()
624                     }, dojo.create("span", null, alert_node, "after")
625                 );
626             }
627         }
628
629         if (openils.Util.isTrue(note.vendor_public()))
630             nodeByName("vendor_public", row).innerHTML =
631                 localeStrings.VENDOR_PUBLIC;
632
633         nodeByName("delete", row).onclick = function() {
634             note.isdeleted(true);
635             self.liNotesTbody.removeChild(row);
636             self.updateLiNotes(li);
637         };
638
639         if(note.edit_time()) {
640             nodeByName("edit_time", row).innerHTML =
641                 dojo.date.locale.format(
642                     dojo.date.stamp.fromISOString(note.edit_time()), 
643                     {formatLength:'short'});
644         }
645
646         self.liNotesTbody.appendChild(row);
647     }
648
649     /**
650      * Updates any new/changed/deleted notes on the server
651      */
652     this.updateLiNotes = function(li, newNote) {
653
654         var notes;
655         if(newNote) {
656             notes = [newNote];
657         } else {
658             notes = li.lineitem_notes().filter(
659                 function(note) {
660                     if(note.ischanged() || note.isnew() || note.isdeleted())
661                         return note;
662                 }
663             );
664         }
665
666         if(notes.length == 0) return;
667         progressDialog.show();
668
669         fieldmapper.standardRequest(
670             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
671             {   async : true,
672                 params : [this.authtoken, notes],
673                 onresponse : function(r) {
674                     var resp = openils.Util.readResponse(r);
675
676                     if(resp.complete) {
677
678                         if(!newNote) {
679                             // remove the old changed notes
680                             var list = [];
681                             dojo.forEach(li.lineitem_notes(), 
682                                 function(note) {
683                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
684                                         list.push(note);
685                                 }
686                             );
687                             li.lineitem_notes(list);
688                         }
689
690                         progressDialog.hide();
691                         self.updateLiNotesCount(li);
692                         self.drawLiNotes(li);
693                         return;
694                     }
695
696                     progressDialog.update(resp);
697                     var newnote = resp.note;
698
699                     if(!newnote.isdeleted()) {
700                         newnote.isnew(false);
701                         newnote.ischanged(false);
702                         li.lineitem_notes().push(newnote);
703                     }
704                 },
705             }
706         );
707     }
708
709     this.updateLiPrice = function(input, li) {
710
711         var price = input.value;
712         if(Number(price) == Number(li.estimated_unit_price())) return;
713
714         fieldmapper.standardRequest(
715             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
716             {   async : true,
717                 params : [this.authtoken, li.id(), price],
718                 oncomplete : function(r) {
719                     openils.Util.readResponse(r);
720                     li.estimated_unit_price(price); // update local copy
721                 }
722             }
723         );
724     }
725
726     this.removeLineitem = function(liId) {
727         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
728         delete this.liCache[liId];
729         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
730     }
731
732     this.drawInfo = function(liId) {
733         if (!this._isRelatedViewer) {
734             var d = dojo.byId("acq-lit-info-related");
735             if (!this.relCache[liId]) {
736                 fieldmapper.standardRequest(
737                     [
738                         "open-ils.acq",
739                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
740                     ], {
741                         "async": true,
742                         "params": [openils.User.authtoken, liId],
743                         "onresponse": function(r) {
744                             self.relCache[liId] = openils.Util.readResponse(r);
745                             nodeByName("related_number", d).innerHTML =
746                                 self.relCache[liId];
747                             openils.Util[
748                                 self.relCache[liId] >1 ? "show" : "hide"
749                             ](d);
750                         }
751                     }
752                 );
753             } else {
754                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
755                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
756             }
757         }
758
759         this.show('info');
760         openils.acq.Lineitem.fetchAttrDefs(
761             function() { 
762                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
763             } 
764         );
765     };
766
767     this._fetchLineitem = function(liId, handler, force) {
768
769         var li = this.liCache[liId];
770         if(li && li.marc() && li.lineitem_details() && !force)
771             return handler(li);
772         
773         fieldmapper.standardRequest(
774             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
775             {   async: true,
776
777                 params: [self.authtoken, liId, {
778                     flesh_attrs: true,
779                     flesh_cancel_reason: true,
780                     flesh_li_details: true,
781                     flesh_notes: true,
782                     flesh_fund_debit: true }],
783
784                 oncomplete: function(r) {
785                     var li = openils.Util.readResponse(r);
786                     handler(li)
787                 }
788             }
789         );
790     };
791
792     this._drawInfo = function(li) {
793
794         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
795
796         if(li.eg_bib_id()) {
797             openils.Util.hide('acq-lit-marc-order-record-label');
798             openils.Util.hide(acqLitEditOrderMarc.domNode);
799             openils.Util.show('acq-lit-marc-real-record-label');
800         } else {
801             openils.Util.show('acq-lit-marc-order-record-label');
802             openils.Util.show(acqLitEditOrderMarc.domNode);
803             openils.Util.hide('acq-lit-marc-real-record-label');
804         }
805
806         this.drawMarcHTML(li);
807         this.infoTbody = dojo.byId('acq-lit-info-tbody');
808
809         if(!this.infoRow)
810             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
811         while(this.infoTbody.childNodes[0])
812             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
813
814         for(var i = 0; i < li.attributes().length; i++) {
815             var attr = li.attributes()[i];
816             var row = this.infoRow.cloneNode(true);
817
818             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
819             var name = openils.acq.Lineitem.attrDefs[type].filter(
820                 function(a) {
821                     return (a.code() == attr.attr_name());
822                 }
823             ).pop().description();
824
825             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
826             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
827             this.infoTbody.appendChild(row);
828         }
829
830         if (!this._isRelatedViewer) {
831             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
832                 oilsBasePath + "/acq/lineitem/related/" + li.id();
833         }
834
835         if(li.eg_bib_id()) {
836
837             openils.Util.show('acq-lit-info-cat-link');
838             var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
839
840             if(openils.XUL.isXUL()) {
841
842                 link.setAttribute('href', 'javascript:void(0);');
843                 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
844
845             } else {
846                 var href = link.getAttribute('href');
847                 if(href.match(/=$/))
848                     link.setAttribute('href',  href + li.eg_bib_id());
849             }
850         } else {
851             openils.Util.hide('acq-lit-info-cat-link');
852         }
853     };
854
855     this.generateMakeRecTab = function(bib_id,default_view, row) {
856         return function() {
857             xulG.new_tab(
858                 XUL_OPAC_WRAPPER,
859                 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
860                 {
861                     no_xulG : false, 
862                     show_nav_buttons : true, 
863                     show_print_button : true, 
864                     opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
865                     default_view : default_view
866                 }
867             );
868
869             if(row) nodeByName("action_none", row).selected = true;
870         }
871     };
872
873     this.drawMarcHTML = function(li) {
874         var params = [null, true, li.marc()];
875         if(li.eg_bib_id()) 
876             params = [li.eg_bib_id(), true];
877
878         fieldmapper.standardRequest(
879             ['open-ils.search', 'open-ils.search.biblio.record.html'],
880             {   async: true,
881                 params: params,
882                 oncomplete: function(r) {
883                     dojo.byId('acq-lit-marc-div').innerHTML = 
884                         openils.Util.readResponse(r);
885                 }
886             }
887         );
888     }
889
890     this.drawCopies = function(liId) {
891         this.show('copies');
892         var self = this;
893         this.copyCache = {};
894         this.copyWidgetCache = {};
895         this.oldCopyWidgetCache = {};
896         this.virtDfaCounts = {};
897         this.realDfaCache = {};
898         this.dfeOffset = 0;
899
900         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
901         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
902         acqLitCopyCountInput.attr('value', '0');
903
904         while(this.copyTbody.childNodes[0])
905             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
906
907         this._drawBatchCopyWidgets();
908
909         this._drawDistribApplied(liId);
910
911         this._fetchDistribFormulas(
912             function() {
913                 openils.acq.Lineitem.fetchAttrDefs(
914                     function() { 
915                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}); 
916                     } 
917                 );
918             }
919         );
920     };
921
922     this._saveDistribAppliedTemplates = function() {
923         if (!this._appliedDistribTemplate) {
924             this._appliedDistribTemplate =
925                 dojo.byId("acq-lit-distrib-applied-tbody").
926                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
927             dojo.attr(this._appliedDistribTemplate, "id");
928         }
929     };
930
931     this._drawDistribApplied = function(liId) {
932         /* Build this table while hidden to prevent rendering artifacts */
933         openils.Util.hide("acq-lit-distrib-applied-tbody");
934
935         this._saveDistribAppliedTemplates();
936
937         /* Remove any rows in the table from previous populations */
938         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
939             forEach(dojo.destroy);
940
941         /* Unregister all dijits previously created (for some reason this isn't
942          * covered by the above destroy calls). */
943         dijit.registry.forEach(
944             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
945         );
946
947         /* Populate the table with our liId */
948         var total = 0;
949         fieldmapper.standardRequest(
950             ["open-ils.acq",
951             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
952             {
953                 "async": true,
954                 "params": [self.authtoken, liId],
955                 "onresponse": function(r) {
956                     var dfa = openils.Util.readResponse(r);
957                     if (dfa) {
958                         total++;
959                         self.realDfaCache[dfa.id()] = dfa;
960                         self._drawDistribAppliedUnit(dfa);
961                     }
962                 },
963                 "oncomplete": function() {
964                     /* Reveal built table */
965                     if (total) {
966                         openils.Util.show(
967                             "acq-lit-distrib-applied-tbody", "table-row-group"
968                         );
969                     }
970                 }
971             }
972         );
973     };
974
975     this._drawDistribAppliedUnit = function(dfa) {
976         var new_row = false;
977         var row = dojo.query(
978             'tr[formula="' + dfa.formula().id() + '"]',
979             "acq-lit-distrib-applied-tbody"
980         )[0];
981
982         if (!row) {
983             new_row = true;
984             row = dojo.clone(this._appliedDistribTemplate);
985             dojo.attr(row, "formula", dfa.formula().id());
986             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
987         }
988
989         var td = dojo.query("td", row)[0];
990
991         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
992         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
993
994         if (new_row)
995             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
996
997         new dijit.form.Button(
998             {
999                 "onClick": function() {
1000                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1001                         self.deleteDfa(dfa);
1002                 },
1003                 "label": "X",
1004                 /* XXX I /cannot/ make the following work in as a CSS class
1005                  * for some reason. So frustrating... */
1006                 "style": function(id) {
1007                      return (id > 0 ?
1008                         "font-weight: bold; color: #c00;" :
1009                         "color: #666;");
1010                      }(dfa.id()) + "margin: 0 6px;display: inline;"
1011             }, "dfa-button-" + dfa.id()
1012         );
1013         new dijit.Tooltip(
1014             {
1015                 "connectId": ["dfa-button-" + dfa.id()],
1016                 "label": dojo.string.substitute(
1017                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
1018                         openils.User.formalName(dfa.creator()),
1019                         dojo.date.locale.format(
1020                             dojo.date.stamp.fromISOString(dfa.create_time()),
1021                             {"formatLength":"short"}
1022                         )
1023                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1024                 )
1025             }, "dfa-tip-" + dfa.id()
1026         );
1027     }
1028
1029     this.deleteDfa = function(dfa) {
1030         if (dfa.id() > 0) { /* real */
1031             this.pcrud.eliminate(
1032                 dfa, {
1033                     "async": true,
1034                     "oncomplete": function() {
1035                         self._removeDistribApplied(dfa.id());
1036                         delete self.realDfaCache[dfa.id()];
1037                     }
1038                 }
1039             );
1040         } else { /* virtual */
1041             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1042             this.virtDfaCounts[dfa.formula().id()] = 0;
1043             /* hasn't been saved yet, so no need to do anything server side */
1044             this._removeDistribApplied(dfa.id());
1045         }
1046
1047     };
1048
1049     this._removeDistribApplied = function(dfaId) {
1050         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1051         dijit.registry.forEach(
1052             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1053         );
1054         this._removeDistribAppliedEmptyRows();
1055     };
1056
1057     this._removeAllDistribAppliedVirtual = function() {
1058         /* Unregister dijits */
1059         dijit.registry.forEach(
1060             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1061         );
1062         this._removeDistribAppliedEmptyRows();
1063     };
1064
1065     this._removeDistribAppliedEmptyRows = function() {
1066         /* Remove any rows with no DFA at all */
1067         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1068             function(o) {
1069                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1070             }
1071         );
1072     };
1073
1074     /**
1075      * Insert a new row into the distribution formula selection form
1076      */
1077     this._addDistribFormulaRow = function() {
1078         var self = this;
1079
1080         if (!self.distribForms) {
1081             // no formulas, hide the form
1082             openils.Util.hide('acq-lit-distrib-formula-tbody');
1083             return;
1084         }
1085
1086         if(!this.distribFormulaTemplate) 
1087             this.distribFormulaTemplate = 
1088                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1089
1090         var row = this.distribFormulaTemplate.cloneNode(true);
1091         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1092
1093         this.dfSelector = new dijit.form.FilteringSelect(
1094             {"labelAttr": "dynLabel", "labelType": "html"},
1095             nodeByName("selector", row)
1096         );
1097         this._updateFormulaStore();
1098         this.dfSelector.fetchProperties =
1099             {"sort": [{"attribute": "use_count", "descending": true}]};
1100
1101         var apply = new dijit.form.Button(
1102             {"label": localeStrings.APPLY},
1103             nodeByName('set_button', row)
1104         ); 
1105
1106         var reset = new dijit.form.Button(
1107             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1108             nodeByName("reset_button", row)  
1109         );
1110
1111         dojo.connect(apply, 'onClick', 
1112             function() {
1113                 var form_id = self.dfSelector.attr("value");
1114                 if(!form_id) return;
1115                 self._applyDistribFormula(form_id);
1116                 reset.attr("disabled", false);
1117             }
1118         );
1119
1120         dojo.connect(reset, 'onClick', 
1121             function() {
1122                 self.restoreCopyFieldsBeforeDF();
1123                 self.virtDfaCounts = {};
1124                 self.virtDfaId = -1;
1125                 self.dfeOffset = 0;
1126                 self._updateFormulaStore();
1127                 self._removeAllDistribAppliedVirtual();
1128                 reset.attr("disabled", "true");
1129             }
1130         );
1131
1132     };
1133
1134     /**
1135      * Applies a distrib formula to the current set of copies
1136      */
1137     this._applyDistribFormula = function(formula) {
1138         if(!formula) return;
1139
1140         formula = this.distribForms.filter(
1141             function(form) { return form.id() == formula; }
1142         )[0];
1143
1144         var copyRows = dojo.query('tr', self.copyTbody);
1145
1146         if (this.dfeOffset >= copyRows.length) {
1147             alert(localeStrings.OUT_OF_COPIES);
1148             return;
1149         }
1150
1151         var entries_applied = 0;
1152         for(
1153             var rowIndex = this.dfeOffset;
1154             rowIndex < copyRows.length;
1155             rowIndex++
1156         ) {
1157             
1158             var row = copyRows[rowIndex];
1159             var copy_id = row.getAttribute('copy_id');
1160             var copyWidgets = this.copyWidgetCache[copy_id];
1161             var entryIndex = this.dfeOffset;
1162             var entry = null;
1163
1164             // find the correct entry for the current row
1165             dojo.forEach(formula.entries(), 
1166                 function(e) {
1167                     if(!entry) {
1168                         entryIndex += e.item_count();
1169                         if(entryIndex > rowIndex)
1170                             entry = e;
1171                     }
1172                 }
1173             );
1174
1175             if(entry) {
1176                 
1177                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
1178                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1179     
1180                 entries_applied++;
1181                 this.saveCopyFieldsBeforeDF(copy_id);
1182                 this._copy_fields_for_acqdf.forEach(
1183                     function(field) {
1184                         if(entry[field]()) {
1185                             copyWidgets[field].attr('value', (entry[field]()));
1186                         }
1187                     }
1188                 );
1189             }
1190         }
1191
1192         if (entries_applied) {
1193             this.virtDfaCounts[formula.id()] =
1194                 ++(this.virtDfaCounts[formula.id()]) || 1;
1195             this._updateFormulaStore();
1196             this._drawDistribAppliedUnit(
1197                 function(df) {
1198                     var dfa = new acqdfa();
1199                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1200                 }(formula)
1201             );
1202             this.dfeOffset += entries_applied;
1203         };
1204     };
1205
1206     /**
1207      * This function updates the DF store for the dropdown so that use_counts
1208      * can reflect DF applications from this session before they're saved
1209      * server-side.
1210      */
1211     this._updateFormulaStore = function() {
1212         this.dfSelector.store = new dojo.data.ItemFileReadStore(
1213             {
1214                 "data": self._labelFormulasWithCounts(
1215                     acqdf.toStoreData(self.distribForms)
1216                 )
1217             }
1218         );
1219     };
1220
1221     this.saveCopyFieldsBeforeDF = function(copy_id) {
1222         var self = this;
1223         if (!this.oldCopyWidgetCache[copy_id]) {
1224             var copyWidgets = this.copyWidgetCache[copy_id];
1225
1226             this.oldCopyWidgetCache[copy_id] = {};
1227             this._copy_fields_for_acqdf.forEach(
1228                 function(f) {
1229                     self.oldCopyWidgetCache[copy_id][f] =
1230                         copyWidgets[f].attr("value");
1231                 }
1232             );
1233         }
1234     };
1235
1236     this.restoreCopyFieldsBeforeDF = function() {
1237         var self = this;
1238         for (var copy_id in this.oldCopyWidgetCache) {
1239             this._copy_fields_for_acqdf.forEach(
1240                 function(f) {
1241                     self.copyWidgetCache[copy_id][f].attr(
1242                         "value", self.oldCopyWidgetCache[copy_id][f]
1243                     );
1244                 }
1245             );
1246         }
1247     };
1248
1249     this._labelFormulasWithCounts = function(store_data) {
1250         for (var key in store_data.items) {
1251             var obj = store_data.items[key];
1252             obj.use_count = Number(obj.use_count); /* needed for sorting */
1253
1254             if (this.virtDfaCounts[obj.id])
1255                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1256
1257             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1258                 obj.use_count + "]</span>&nbsp; " + obj.name;
1259         }
1260         return store_data;
1261     };
1262
1263     /**
1264      * This method formerly would not refetch the DF formulas if they'd been
1265      * loaded already, but now it always re-fetches, since use_count changes.
1266      */
1267     this._fetchDistribFormulas = function(onload) {
1268         fieldmapper.standardRequest(
1269             ["open-ils.acq",
1270                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1271             {
1272                 "async": true,
1273                 "params": [openils.User.authtoken],
1274                 "oncomplete": function(r) {
1275                     self.distribForms = openils.Util.readResponse(r);
1276                     if(!self.distribForms || self.distribForms.length == 0) {
1277                         self.distribForms = [];
1278                     }
1279                     self._addDistribFormulaRow();
1280                     onload();
1281                 }
1282             }
1283         );
1284     }
1285
1286     this._drawBatchCopyWidgets = function() {
1287         var row = this.copyBatchRow;
1288         dojo.forEach(liDetailBatchFields, 
1289             function(field) {
1290                 if(self.copyBatchRowDrawn) {
1291                     self.copyBatchWidgets[field].attr('value', null);
1292                 } else {
1293                     var widget = new openils.widget.AutoFieldWidget({
1294                         fmField : field,
1295                         fmClass : 'acqlid',
1296                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1297                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1298                         searchFilter : (field == 'fund') ? {"active": "t"} : null,
1299                         parentNode : dojo.query('[name='+field+']', row)[0],
1300                         orgLimitPerms : ['CREATE_PICKLIST'],
1301                         dijitArgs : {
1302                             "required": false,
1303                             "labelType": (field == "fund") ? "html" : null
1304                         },
1305                         noCache: (field == "fund"),
1306                         forceSync : true
1307                     });
1308                     widget.build(
1309                         function(w, ww) {
1310                             if (field == "fund" && w.store)
1311                                 self._ensureCSSFundClasses(w.store);
1312                             self.copyBatchWidgets[field] = w;
1313                         }
1314                     );
1315                     if (field == "fund") {
1316                         dojo.connect(
1317                             widget.widget, "onChange", function(val) {
1318                                 self._updateFundSelectorStyle(widget, val);
1319                             }
1320                         );
1321                     }
1322                 }
1323             }
1324         );
1325         this.copyBatchRowDrawn = true;
1326     };
1327
1328     this.batchCopyUpdate = function() {
1329         var self = this;
1330         for(var k in this.copyWidgetCache) {
1331             var cache = this.copyWidgetCache[k];
1332             dojo.forEach(liDetailBatchFields, function(f) {
1333                 var newval = self.copyBatchWidgets[f].attr('value');
1334                 if(newval) cache[f].attr('value', newval);
1335             });
1336         }
1337     };
1338
1339     this._drawCopies = function(li) {
1340         var self = this;
1341
1342         // this button sets the total number of copies for a given lineitem
1343         acqLitAddCopyCount.onClick = function() { 
1344             var count = acqLitCopyCountInput.attr('value');
1345
1346             // add new rows
1347             while(self.copyCount() < count)
1348                 self.addCopy(li); 
1349             
1350             // delete rows if necessary
1351             var diff = self.copyCount() - count;
1352             if(diff > 0) {
1353                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1354                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1355                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1356                 } else {
1357                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1358                 }
1359             }
1360         }
1361
1362
1363         if(li.lineitem_details().length > 0) {
1364             dojo.forEach(li.lineitem_details(),
1365                 function(copy) {
1366                     self.addCopy(li, copy);
1367                 }
1368             );
1369         } else {
1370             self.addCopy(li);
1371         }
1372     };
1373
1374     this.copyCount = function() {
1375         var count = 0;
1376         for(var id in this.copyCache) {
1377             if(!this.copyCache[id].isdeleted())
1378                 count++;
1379         }
1380         return count;
1381     }
1382
1383     this.virtCopyId = -1;
1384     this.addCopy = function(li, copy) {
1385         var row = this.copyRow.cloneNode(true);
1386         this.copyTbody.appendChild(row);
1387         var self = this;
1388
1389         if(!copy) {
1390             copy = new fieldmapper.acqlid();
1391             copy.isnew(true);
1392             copy.id(this.virtCopyId--);
1393             copy.lineitem(li.id());
1394         }
1395
1396         this.copyCache[copy.id()] = copy;
1397         row.setAttribute('copy_id', copy.id());
1398         self.copyWidgetCache[copy.id()] = {};
1399
1400         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1401
1402         dojo.forEach(liDetailFields,
1403             function(field) {
1404                 var searchFilter;
1405                 if (field == "fund") {
1406                     searchFilter = (copy.fund() ?
1407                         {"-or": {"active": "t", "id": copy.fund()}} :
1408                         {"active" : "t"});
1409                 } else {
1410                     searchFilter = null;
1411                 }
1412
1413                 var readOnly = false;
1414                 
1415                 // TODO: Add support for changing the owning_lib after real copies have been made.  
1416                 // owning_lib is order data as much as its item data
1417                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1418                     readOnly = true;
1419                 }
1420
1421                 // TODO: add support for changing the fund after debits have been created
1422                 // Note: invoicing allows the change
1423                 if(copy.fund_debit() && field == 'fund') {
1424                     readOnly = true;
1425                 }
1426
1427                 var widget = new openils.widget.AutoFieldWidget({
1428                     fmObject : copy,
1429                     fmField : field,
1430                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1431                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1432                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1433                     searchFilter : searchFilter,
1434                     noCache: (field == "fund"),
1435                     fmClass : 'acqlid',
1436                     parentNode : dojo.query('[name='+field+']', row)[0],
1437                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1438                     readOnly : readOnly,
1439                 });
1440                 widget.build(
1441                     // make sure we capture the value from any async widgets
1442                     function(w, ww) { 
1443                         if (field == "fund" && w.store)
1444                             self._ensureCSSFundClasses(w.store);
1445                         copy[field](ww.getFormattedValue()) 
1446                         self.copyWidgetCache[copy.id()][field] = w;
1447                     }
1448                 );
1449                 dojo.connect(widget.widget, 'onChange', 
1450                     function(val) { 
1451                         if (field == "fund")
1452                             self._updateFundSelectorStyle(widget, val);
1453
1454                         if (copy.isnew() || val != copy[field]()) {
1455                             // prevent setting ischanged() automatically on widget load for existing copies
1456                             copy[field](widget.getFormattedValue()) 
1457                             copy.ischanged(true);
1458                         }
1459                     }
1460                 );
1461             }
1462         );
1463
1464         this.updateLidState(copy, row);
1465     };
1466
1467     this._ensureCSSFundClass = function(id) {
1468         if (!this.fundStyleSheet) {
1469             dojo.create(
1470                 "style", {"type": "text/css"},
1471                 document.getElementsByTagName("head")[0], "last"
1472             );
1473             this.fundStyleSheet = document.styleSheets[
1474                 document.styleSheets.length - 1
1475             ];
1476         }
1477
1478         var cn = "fund_" + id;
1479         if (!this.haveFundClass[cn]) {
1480             fieldmapper.standardRequest(
1481                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1482                 {
1483                     "params": [openils.User.authtoken, id],
1484                     "async": true,
1485                     "oncomplete": function(r) {
1486                         r = openils.Util.readResponse(r);
1487                         self.fundBalanceState[id] = r;
1488                         var style = "";
1489                         if (r[0] /* stop */)
1490                             style = fundStyles.stop;
1491                         else if (r[1] /* warning */)
1492                             style = fundStyles.warning;
1493                         self.fundStyleSheet.insertRule(
1494                             "." + cn + " { " + style + " }",
1495                             self.fundStyleSheet.cssRules.length
1496                         );
1497                         self.haveFundClass[cn] = true;
1498                     }
1499                 }
1500             );
1501         }
1502     };
1503
1504     this._ensureCSSFundClasses = function(store) {
1505         store.fetch({
1506             "query": {"id": "*"},
1507             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1508         });
1509     };
1510
1511     this._updateFundSelectorStyle = function(widget, fund_id) {
1512         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1513         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1514     };
1515
1516     this.updateLidState = function(copy, row) {
1517         if (typeof(row) == "undefined") {
1518             row = dojo.query(
1519                 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1520             )[0];
1521         }
1522
1523         var self = this;
1524         var recv_link = nodeByName("receive", row);
1525         var unrecv_link = nodeByName("unreceive", row);
1526         var del_link = nodeByName("delete", row);
1527         var cxl_link = nodeByName("cancel", row);
1528         var claim_link = nodeByName("claim", row);
1529         var cxl_reason_link = nodeByName("cancel_reason", row);
1530
1531         if (copy.cancel_reason()) {
1532             openils.Util.hide(del_link.parentNode);
1533             openils.Util.hide(recv_link);
1534             openils.Util.hide(unrecv_link);
1535             openils.Util.hide(cxl_link);
1536             openils.Util.hide(claim_link);
1537
1538             /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1539             var holds_reason = dojo.create(
1540                 "span", {
1541                     "style": "border-bottom: 1px dashed #000;",
1542                     "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1543                 }, cxl_reason_link, "only"
1544             );
1545             new dijit.Tooltip(
1546                 {
1547                     "label": "<em>" + copy.cancel_reason().label() +
1548                         "</em><br />" + copy.cancel_reason().description(),
1549                     "connectId": [holds_reason]
1550                 }, dojo.create("span", null, cxl_reason_link, "last")
1551             );
1552             openils.Util.show(cxl_reason_link, "inline");
1553         } else if (this.isPO) {
1554             /* Only using this in one place so far, but may want it for better
1555              * decisions on when to display certain controls. */
1556             var li_state = this.liCache[copy.lineitem()].state();
1557
1558             openils.Util.hide(del_link.parentNode);
1559             openils.Util.hide(cxl_reason_link);
1560
1561             /* Avoid showing (un)receive links, cancel links, for virt copies */
1562             if (copy.id() > 0) {
1563                 if (copy.recv_time()) {
1564                     openils.Util.hide(cxl_link);
1565                     openils.Util.hide(recv_link);
1566                     openils.Util.hide(claim_link);
1567
1568                     openils.Util.show(unrecv_link, "inline");
1569                     unrecv_link.onclick = function() {
1570                         if (confirm(localeStrings.UNRECEIVE_LID))
1571                             self.issueReceive(copy, /* rollback */ true);
1572                     };
1573                 } else {
1574                     openils.Util.hide(unrecv_link);
1575
1576                     if (this.claimEligibleLid[copy.id()]) {
1577                         openils.Util.show(claim_link, "inline");
1578                         claim_link.onclick = function() {
1579                             self.claimDialog.show(
1580                                 self.liCache[copy.lineitem()], copy.id()
1581                             );
1582                         };
1583                     } else {
1584                         openils.Util.hide(claim_link);
1585                     }
1586
1587                     openils.Util[li_state == "on-order" ? "show" : "hide"](
1588                         recv_link, "inline"
1589                     );
1590                     openils.Util.show(cxl_link, "inline");
1591                     recv_link.onclick = function() {
1592                         if (self.checkLiAlerts(copy.lineitem()))
1593                             self.issueReceive(copy);
1594                     };
1595                     cxl_link.onclick = function() {
1596                         self.cancelLid(copy.id());
1597                     };
1598                 }
1599             } else {
1600                 openils.Util.hide(cxl_link);
1601                 openils.Util.hide(unrecv_link);
1602                 openils.Util.hide(recv_link);
1603                 openils.Util.hide(claim_link);
1604             }
1605         } else {
1606             openils.Util.hide(unrecv_link);
1607             openils.Util.hide(recv_link);
1608             openils.Util.hide(cxl_reason_link);
1609             openils.Util.hide(claim_link);
1610
1611             del_link.onclick = function() { self.deleteCopy(row) };
1612             openils.Util.show(del_link.parentNode);
1613         }
1614     }
1615
1616     this.cancelLid = function(lid_id) {
1617         lidCancelDialog._lid_id = lid_id;
1618         openils.Util.show(lidCancelDialog.domNode.parentNode);
1619         lidCancelDialog.show();
1620         if (!lidCancelDialog._prepared) {
1621             var widget = new openils.widget.AutoFieldWidget({
1622                 "fmField": "cancel_reason",
1623                 "fmClass": "acqlid",
1624                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1625                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1626                 "forceSync": true
1627             });
1628             widget.build(
1629                 function(w, ww) {
1630                     acqLidCancelButton.onClick = function() {
1631                         if (w.attr("value")) {
1632                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1633                                 self._cancelLid(
1634                                     lidCancelDialog._lid_id,
1635                                     w.attr("value")
1636                                 );
1637                             }
1638                             lidCancelDialog.hide();
1639                         }
1640                     };
1641                     lidCancelDialog._prepared = true;
1642                 }
1643             );
1644         }
1645     };
1646
1647     this._cancelLid = function(lid_id, reason) {
1648         fieldmapper.standardRequest(
1649             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1650                 "params": [openils.User.authtoken, lid_id, reason],
1651                 "async": true,
1652                 "onresponse": function(r) {
1653                     if (r = openils.Util.readResponse(r)) {
1654                         if (r.lid) {
1655                             for (var id in r.lid) {
1656                                 /* actually this should only iterate once */
1657                                 self.copyCache[id].cancel_reason(
1658                                     r.lid[id].cancel_reason
1659                                 );
1660                                 self.updateLidState(self.copyCache[id]);
1661                             }
1662                         }
1663                     }
1664                 }
1665             }
1666         );
1667     };
1668
1669     this._confirmAlert = function(li, lin) {
1670         return confirm(
1671             dojo.string.substitute(
1672                 localeStrings.CONFIRM_LI_ALERT, [
1673                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1674                         "title", "lineitem_marc_attr_definition"
1675                     ),
1676                     lin.alert_text().code(),
1677                     lin.alert_text().description() || "",
1678                     lin.value()
1679                 ]
1680             )
1681         );
1682     };
1683
1684     this.checkLiAlerts = function(li_id) {
1685         var li = this.liCache[li_id];
1686
1687         var alert_notes = li.lineitem_notes().filter(
1688             function(o) { return Boolean(o.alert_text()); }
1689         );
1690
1691         /* this is _intentionally_ not done in a call to forEach() ... */
1692         for (var i = 0; i < alert_notes.length; i++) {
1693             if (this.noteAcks[alert_notes[i].id()])
1694                 continue;
1695             else if (!this._confirmAlert(li, alert_notes[i]))
1696                 return false;
1697             else
1698                 this.noteAcks[alert_notes[i].id()] = true;
1699         }
1700
1701         return true;
1702     };
1703
1704     this.deleteCopy = function(row) {
1705         var copy = this.copyCache[row.getAttribute('copy_id')];
1706         copy.isdeleted(true);
1707         if(copy.isnew())
1708             delete this.copyCache[copy.id()];
1709         this.copyTbody.removeChild(row);
1710     }
1711
1712     this._virtDfaCountsAsList = function() {
1713         var L = [];
1714         for (var key in this.virtDfaCounts) {
1715             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1716                 L.push(key);
1717         }
1718         return L;
1719     }
1720
1721     this.confirmBreachedCopyFunds = function(copies) {
1722         var stop = 0, warning = 0;
1723         copies.forEach(
1724             function(o) {
1725                 if (o.fund()) {
1726                     var state = self.fundBalanceState[o.fund()];
1727                     if (state[0] /* stop */)
1728                         stop++;
1729                     else if (state[1] /* warning */)
1730                         warning++;
1731                 }
1732             }
1733         );
1734
1735         if (stop) {
1736             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1737         } else if (warning) {
1738             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1739         }
1740         return true;
1741     };
1742
1743     this.saveCopyChanges = function(liId) {
1744         var self = this;
1745         var copies = [];
1746
1747
1748         var total = 0;
1749         for(var id in this.copyCache) {
1750             var c = this.copyCache[id];
1751             if(!c.isdeleted()) total++;
1752             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1753                 if(c.id() < 0) c.id(null);
1754                 copies.push(c);
1755             }
1756         }
1757
1758
1759         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1760
1761
1762         if (copies.length > 0) {
1763             if (!this.confirmBreachedCopyFunds(copies))
1764                 return;
1765
1766             if (typeof(this._copy_count_cb) == "function")
1767                 this._copy_count_cb(liId, total);
1768
1769             openils.Util.show("acq-lit-update-copies-progress");
1770             fieldmapper.standardRequest(
1771                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1772                 {   async: true,
1773                     params: [openils.User.authtoken, copies],
1774                     onresponse: function(r) {
1775                         var res = openils.Util.readResponse(r);
1776                         litUpdateCopiesProgress.update(res);
1777                     },
1778                     oncomplete: function() {
1779                         self.drawCopies(liId);
1780                         openils.Util.hide("acq-lit-update-copies-progress");
1781                     }
1782                 }
1783             );
1784         }
1785
1786         var dfa_list = this._virtDfaCountsAsList();
1787         if (dfa_list.length > 0) {
1788             fieldmapper.standardRequest(
1789                 ["open-ils.acq",
1790                 "open-ils.acq.distribution_formula.record_application"],
1791                 {
1792                     "async": true,
1793                     "params": [openils.User.authtoken, dfa_list, liId],
1794                     "onresponse": function(r) {
1795                         var res = openils.Util.readResponse(r);
1796                         if (res && res.length < dfa_list.length)
1797                             alert(localeStrings.DFA_NOT_ALL);
1798                     }
1799                 }
1800             );
1801             this.virtDfaCounts = {};
1802         }
1803     }
1804
1805     this._updateCreatePoPrepayCheckbox = function(prepay) {
1806         var prepay = openils.Util.isTrue(prepay);
1807         this._prepayRequiredByVendor = prepay;
1808         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1809     };
1810
1811     this._confirmPoPrepaySituation = function() {
1812         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1813         if (want_prepay != this._prepayRequiredByVendor) {
1814             return confirm(
1815                 want_prepay ?
1816                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1817                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1818             );
1819         } else {
1820             return true;
1821         }
1822     };
1823
1824     this.applySelectedLiAction = function(action) {
1825         var self = this;
1826         switch(action) {
1827
1828             case 'delete_selected':
1829                 this._deleteLiList(self.getSelected());
1830                 break;
1831
1832             case 'create_order':
1833
1834                 if(!this.createPoProviderSelector) {
1835                     var widget = new openils.widget.AutoFieldWidget({
1836                         fmField : 'provider',
1837                         fmClass : 'acqpo',
1838                         searchFilter: {"active": "t"},
1839                         parentNode : dojo.byId('acq-lit-po-provider'),
1840                         dijitArgs : {
1841                             "onChange": function() {
1842                                 if (this.item) {
1843                                     self._updateCreatePoPrepayCheckbox(
1844                                         this.item.prepayment_required
1845                                     );
1846                                 }
1847                             }
1848                         }
1849                     });
1850                     widget.build(
1851                         function(w) { self.createPoProviderSelector = w; }
1852                     );
1853                 }
1854
1855                 if(!this.createPoAgencySelector) {
1856                     var widget = new openils.widget.AutoFieldWidget({
1857                         fmField : 'ordering_agency',
1858                         fmClass : 'acqpo',
1859                         parentNode : dojo.byId('acq-lit-po-agency'),
1860                         orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1861                     });
1862                     widget.build(
1863                         function(w) { self.createPoAgencySelector = w; }
1864                     );
1865                 }
1866
1867          
1868                 acqLitPoCreateDialog.show();
1869                 break;
1870
1871             case 'save_picklist':
1872                 this._loadPLSelect();
1873                 acqLitSavePlDialog.show();
1874                 break;
1875
1876             case 'selector_ready':
1877             case 'order_ready':
1878                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1879                 acqLitChangeLiStateDialog.show();
1880                 break;
1881
1882             case 'print_po':
1883                 this.printPO();
1884                 break;
1885
1886             case 'po_history':
1887                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
1888                 break;
1889
1890             case 'receive_po':
1891                 this.receivePO();
1892                 break;
1893
1894             case 'rollback_receive_po':
1895                 this.rollbackPoReceive();
1896                 break;
1897
1898             case 'create_assets':
1899                 this.createAssets();
1900                 break;
1901
1902             case 'export_attr_list':
1903                 this.chooseExportAttr();
1904                 break;
1905
1906             case 'batch_apply_funds':
1907                 this.applyBatchLiFunds();
1908                 break;
1909
1910             case 'add_brief_record':
1911                 if(this.isPO)
1912                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1913                 else
1914                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1915
1916                 break;
1917
1918             case "cancel_lineitems":
1919                 this.maybeCancelLineitems();
1920                 break;
1921
1922             case "change_claim_policy":
1923                 var li_list = this.getSelected();
1924                 this.claimPolicyPicker.attr("value", null);
1925                 liClaimPolicyDialog.show();
1926                 liClaimPolicySave.onClick = function() {
1927                     self.changeClaimPolicy(
1928                         li_list,
1929                         self.claimPolicyPicker.attr("value"),
1930                         function() {
1931                             li_list.forEach(
1932                                 function(li) { self.setClaimPolicyControl(li); }
1933                             );
1934                             liClaimPolicyDialog.hide();
1935                         }
1936                     )
1937                 };
1938                 break;
1939         }
1940     };
1941
1942     this.changeClaimPolicy = function(li_list, value, callback) {
1943         li_list.forEach(
1944             function(li) { li.claim_policy(value); }
1945         );
1946         fieldmapper.standardRequest(
1947             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
1948                 "params": [openils.User.authtoken, li_list],
1949                 "async": true,
1950                 "oncomplete": function(r) {
1951                     r = openils.Util.readResponse(r);
1952                     if (callback) callback(r);
1953                 }
1954             }
1955         );
1956     };
1957
1958     this.createAssets = function() {
1959         if(!this.isPO) return;
1960         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1961         this.show('acq-lit-progress-numbers');
1962         var self = this;
1963         fieldmapper.standardRequest(
1964             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1965             {   async: true,
1966                 params: [this.authtoken, this.isPO],
1967                 onresponse: function(r) {
1968                     var resp = openils.Util.readResponse(r);
1969                     self._updateProgressNumbers(resp, true);
1970                 }
1971             }
1972         );
1973     }
1974
1975     this.maybeCancelLineitems = function() {
1976         openils.Util.show("acq-lit-cancel-reason", "inline");
1977         if (!acqLitCancelLineitemsButton._prepared) {
1978             var widget = new openils.widget.AutoFieldWidget({
1979                 "fmField": "cancel_reason",
1980                 "fmClass": "jub",
1981                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1982                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1983                 "forceSync": true
1984             });
1985             widget.build(
1986                 function(w, ww) {
1987                     acqLitCancelLineitemsButton.onClick = function() {
1988                         if (w.attr("value")) {
1989                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1990                                 self._cancelLineitems(w.attr("value"));
1991                             }
1992                             openils.Util.hide("acq-lit-cancel-reason");
1993                         }
1994                     };
1995                     acqLitCancelLineitemsButton._prepared = true;
1996                 }
1997             );
1998         }
1999     };
2000
2001     this._cancelLineitems = function(reason) {
2002         var id_list = this.getSelected().map(function(o) { return o.id(); });
2003         fieldmapper.standardRequest(
2004             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2005                 "params": [openils.User.authtoken, id_list, reason],
2006                 "async": true,
2007                 "onresponse": function(r) {
2008                     if (r = openils.Util.readResponse(r)) {
2009                         if (r.li) {
2010                             for (var id in r.li) {
2011                                 self.liCache[id].state(r.li[id].state);
2012                                 self.liCache[id].cancel_reason(
2013                                     r.li[id].cancel_reason
2014                                 );
2015                                 self.updateLiState(self.liCache[id]);
2016                             }
2017                         }
2018                         if (r.lid && self.copyCache) {
2019                             for (var id in r.lid) {
2020                                 if (self.copyCache[id]) {
2021                                     self.copyCache[id].cancel_reason(
2022                                         r.lid[id].cancel_reason
2023                                     );
2024                                     self.updateLidState(self.copyCache[id]);
2025                                 }
2026                             }
2027                         }
2028                     }
2029                 }
2030             }
2031         );
2032     };
2033
2034     this.chooseExportAttr = function() {
2035         if (!acqLitExportAttrSelector._li_setup) {
2036             var self = this;
2037             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2038                 {
2039                     "data": acqliad.toStoreData(
2040                         this.pcrud.search(
2041                             "acqliad", {"code": li_exportable_attrs}
2042                         )
2043                     )
2044                 }
2045             );
2046             acqLitExportAttrSelector.setValue();
2047             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2048             acqLitExportAttrSelector._li_setup = true;
2049         }
2050         openils.Util.show("acq-lit-export-attr-holder", "inline");
2051     };
2052
2053     this.exportAttrList = function() {
2054         var attr_def = acqLitExportAttrSelector.item;
2055         var li_list = this.getSelected();
2056         var value_list = li_list.map(
2057             function(li) {
2058                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2059                     attr_def.code, "lineitem_marc_attr_definition"
2060                 );
2061             }
2062         ).filter(function(attr) { return Boolean(attr); });
2063
2064         if (value_list.length > 0) {
2065             if (value_list.length < li_list.length) {
2066                 if (!confirm(
2067                     dojo.string.substitute(
2068                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2069                     )
2070                 )) {
2071                     return;
2072                 }
2073             }
2074             try {
2075                 openils.XUL.contentToFileSaveDialog(
2076                     value_list.join("\n"),
2077                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
2078                 );
2079             } catch (E) {
2080                 alert(E);
2081             }
2082         } else {
2083             alert(dojo.string.substitute(
2084                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2085             ));
2086         }
2087
2088         openils.Util.hide("acq-lit-export-attr-holder");
2089     };
2090
2091     this.printPO = function() {
2092         if(!this.isPO) return;
2093         progressDialog.show(true);
2094         fieldmapper.standardRequest(
2095             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2096             {   async: true,
2097                 params: [this.authtoken, this.isPO, 'html'],
2098                 oncomplete: function(r) {
2099                     progressDialog.hide();
2100                     var evt = openils.Util.readResponse(r);
2101                     if(evt && evt.template_output()) {
2102                         win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
2103                         win.document.body.innerHTML = evt.template_output().data();
2104                     }
2105                 }
2106             }
2107         );
2108     }
2109
2110
2111     this.receivePO = function() {
2112         if (!this.isPO) return;
2113
2114         for (var id in this.liCache) {
2115             /* assumption: liCache reflects exactly the
2116              * set of LIs that belong to our PO */
2117             if (this.liCache[id].state() != "received" &&
2118                 !this.checkLiAlerts(id)) return;
2119         }
2120
2121         this.show('acq-lit-progress-numbers');
2122         var self = this;
2123         fieldmapper.standardRequest(
2124             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2125             {   async: true,
2126                 params: [this.authtoken, this.isPO],
2127                 onresponse : function(r) {
2128                     var resp = openils.Util.readResponse(r);
2129                     self._updateProgressNumbers(resp, true);
2130                 },
2131             }
2132         );
2133     }
2134
2135     this.issueReceive = function(obj, rollback) {
2136         /* (For now) there shall be no marking LI or LIDs (un)received
2137          * except from the actual "view PO" interface. */
2138         if (!this.isPO) return;
2139
2140         var part =
2141             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2142         var method =
2143             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2144
2145         progressDialog.show(true);
2146         fieldmapper.standardRequest(
2147             ["open-ils.acq", method], {
2148                 "async": true,
2149                 "params": [this.authtoken, obj.id()],
2150                 "onresponse": function(r) {
2151                     if (r = openils.Util.readResponse(r)) {
2152                         self.fetchClaimInfo(
2153                             part == "lineitem" ? obj.id() : obj.lineitem(),
2154                             /* force */ true,
2155                             function() { self.handleReceive(r); }
2156                         );
2157                         progressDialog.hide();
2158                     }
2159                 }
2160             }
2161         );
2162     };
2163
2164     /**
2165      * Handles the responses from receive and rollback ML calls.
2166      */
2167     this.handleReceive = function(resp) {
2168         if (resp) {
2169             if (resp.li) {
2170                 for (var li_id in resp.li) {
2171                     for (var key in resp.li[li_id])
2172                         self.liCache[li_id][key](resp.li[li_id][key]);
2173                     self.updateLiState(self.liCache[li_id]);
2174                 }
2175             }
2176             if (resp.po) {
2177                 if (typeof(self.poUpdateCallback) == "function")
2178                     self.poUpdateCallback(resp.po);
2179             }
2180             if (resp.lid) {
2181                 for (var lid_id in resp.lid) {
2182                     for (var key in resp.lid[lid_id])
2183                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2184                     self.updateLidState(self.copyCache[lid_id]);
2185                 }
2186             }
2187         }
2188     };
2189
2190     this.rollbackPoReceive = function() {
2191         if(!this.isPO) return;
2192         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2193         this.show('acq-lit-progress-numbers');
2194         var self = this;
2195         fieldmapper.standardRequest(
2196             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2197             {   async: true,
2198                 params: [this.authtoken, this.isPO],
2199                 onresponse : function(r) {
2200                     var resp = openils.Util.readResponse(r);
2201                     self._updateProgressNumbers(resp, true);
2202                 },
2203             }
2204         );
2205     }
2206
2207     this._updateProgressNumbers = function(resp, reloadOnComplete) {
2208         if(!resp) return;
2209         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
2210         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
2211         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
2212         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
2213         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
2214         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
2215         if(resp.complete && reloadOnComplete) 
2216             location.href = location.href;
2217     }
2218
2219
2220     this._createPO = function(fields) {
2221         this.show('acq-lit-progress-numbers');
2222         var po = new fieldmapper.acqpo();
2223         po.provider(this.createPoProviderSelector.attr('value'));
2224         po.ordering_agency(this.createPoAgencySelector.attr('value'));
2225         po.prepayment_required(fields.prepayment_required[0] ? true : false);
2226
2227         var selected = this.getSelected( (fields.create_from == 'all') );
2228         if(selected.length == 0) return;
2229
2230         var max = selected.length * 3;
2231
2232         var self = this;
2233         fieldmapper.standardRequest(
2234             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
2235             {   async: true,
2236                 params: [
2237                     openils.User.authtoken, 
2238                     po, 
2239                     {
2240                         lineitems : selected.map(function(li) { return li.id() }),
2241                         create_assets : fields.create_assets[0],
2242                     }
2243                 ],
2244
2245                 onresponse : function(r) {
2246                     var resp = openils.Util.readResponse(r);
2247                     self._updateProgressNumbers(resp);
2248                     if(resp.complete) 
2249                         location.href = oilsBasePath + '/acq/po/view/' + resp.purchase_order.id();
2250                 }
2251             }
2252         );
2253     }
2254
2255     this.batchFundWidget = null;
2256
2257     this.applyBatchLiFunds = function() {
2258
2259         var liIds = this.getSelected().map(function(li) { return li.id(); });
2260         if(liIds.length == 0) return; // warn?
2261
2262         var self = this;
2263         batchFundUpdateDialog.show();
2264
2265         if(!this.batchFundWidget) {
2266             this.batchFundWidget = new openils.widget.AutoFieldWidget({
2267                 fmClass : 'acqf',
2268                 selfReference : true,
2269                 labelFormat : fundLabelFormat,
2270                 searchFormat : fundSearchFormat,
2271                 searchFilter : {"active": "t"},
2272                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2273                 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2274                 dijitArgs : { "required": true, "labelType": "html" },
2275                 forceSync : true
2276             });
2277             this.batchFundWidget.build();
2278         }
2279
2280         dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2281         dojo.connect(batchFundUpdateSubmit, 'onClick', 
2282             function() { 
2283
2284                 // TODO: call .dry_run first to test thresholds
2285                 fieldmapper.standardRequest(
2286                     ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2287                     {
2288                         params : [
2289                             openils.User.authtoken, 
2290                             liIds,
2291                             self.batchFundWidget.widget.attr('value')
2292                         ],
2293                         oncomplete : function(r) {
2294                             var resp = openils.Util.readResponse(r);
2295                             if(resp) {
2296                                 location.href = location.href;
2297                             }
2298                         }
2299                     }
2300                 )
2301             }
2302         );
2303     }
2304
2305     this._deleteLiList = function(list, idx) {
2306         if(idx == null) idx = 0;
2307         if(idx >= list.length) return;
2308         var liId = list[idx].id();
2309         fieldmapper.standardRequest(
2310             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
2311             {   async: true,
2312                 params: [openils.User.authtoken, liId],
2313                 oncomplete: function(r) {
2314                     self.removeLineitem(liId);
2315                     self._deleteLiList(list, ++idx);
2316                 }
2317             }
2318         );
2319     }
2320
2321     this.editOrderMarc = function(li) {
2322
2323         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
2324             to true in about:config */
2325
2326         if(!openils.XUL.enableXPConnect()) return;
2327
2328         if(openils.XUL.isXUL()) {
2329             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2330         } else {
2331             win = window.open('/xul/server/cat/marcedit.xul'); 
2332         }
2333         var self = this;
2334         win.xulG = {
2335             record : {marc : li.marc()},
2336             save : {
2337                 label: 'Save Record', // XXX I18N
2338                 func: function(xmlString) {
2339                     li.marc(xmlString);
2340                     fieldmapper.standardRequest(
2341                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2342                         {   async: true,
2343                             params: [openils.User.authtoken, li],
2344                             oncomplete: function(r) {
2345                                 openils.Util.readResponse(r);
2346                                 win.close();
2347                                 self.drawInfo(li.id())
2348                             }
2349                         }
2350                     );
2351                 },
2352             }
2353         };
2354     }
2355
2356     this._savePl = function(values) {
2357         var self = this;
2358         var selected = this.getSelected( (values.which == 'all') );
2359         openils.Util.show('acq-lit-generic-progress');
2360
2361         if(values.new_name) {
2362             openils.acq.Picklist.create(
2363                 {name: values.new_name}, 
2364                 function(id) {
2365                     self._updateLiList(id, selected, 0, 
2366                         function(){
2367                             location.href = oilsBasePath + '/acq/picklist/view/' + id;
2368                         });
2369                 }
2370             );
2371         } else if(values.existing_pl) {
2372             // update lineitems to use an existing picklist
2373             self._updateLiList(values.existing_pl, selected, 0, 
2374                 function(){
2375                     location.href = oilsBasePath + '/acq/picklist/view/' + values.existing_pl;
2376                 });
2377         }
2378     }
2379
2380     this._updateLiState = function(values, state) {
2381         var self = this;
2382         var selected = this.getSelected( (values.which == 'all') );
2383         if(!selected.length) return;
2384         dojo.forEach(selected, function(li) {li.state(state);});
2385         self._updateLiList(null, selected, 0, 
2386             // TODO consider inline updates for efficiency
2387             function() { location.href = location.href }
2388         );
2389     }
2390
2391     this._updateLiList = function(pl, list, idx, oncomplete) {
2392         if(idx >= list.length) return oncomplete();
2393         var li = list[idx];
2394         if(pl != null) li.picklist(pl);
2395         litGenericProgress.update({maximum: list.length, progress: idx});
2396         new openils.acq.Lineitem({lineitem:li}).update(
2397             function(r) {
2398                 self._updateLiList(pl, list, ++idx, oncomplete);
2399             }
2400         );
2401     }
2402
2403     this._loadPLSelect = function() {
2404         if(this._plSelectLoaded) return;
2405         var plList = [];
2406         function handleResponse(r) {
2407             plList.push(r.recv().content());
2408         }
2409         var method = 'open-ils.acq.picklist.user.retrieve';
2410         fieldmapper.standardRequest(
2411             ['open-ils.acq', method],
2412             {   async: true,
2413                 params: [this.authtoken],
2414                 onresponse: handleResponse,
2415                 oncomplete: function() {
2416                     self._plSelectLoaded = true;
2417                     acqLitAddExistingSelect.store = 
2418                         new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2419                     acqLitAddExistingSelect.setValue();
2420                 }
2421             }
2422         );
2423     }
2424
2425     this.showRealCopyEditUI = function(li) {
2426         copyList = [];
2427         var self = this;
2428         this.volCache = {};
2429
2430         this._fetchLineitem(li.id(), 
2431             function(fullLi) {
2432                 li = self.liCache[li.id()] = fullLi;
2433
2434                 self.pcrud.search(
2435                     'acp', {
2436                         id : li.lineitem_details().map(
2437                             function(item) { return item.eg_copy_id() }
2438                         )
2439                     }, {
2440                         async : true,
2441                         oncomplete : function(r) {
2442                             try {
2443                                 var r_list = openils.Util.readResponse( r );
2444                                 for (var i = 0; i < r_list.length; i++) {
2445                                     var copy = r_list[i];
2446                                     var volId = copy.call_number();
2447                                     var volume = self.volCache[volId];
2448                                     if(!volume) {
2449                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2450                                     }
2451                                     copy.call_number(volume);
2452                                     copyList.push(copy);
2453                                 }
2454                                 if (xulG) {
2455                                     // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2456                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
2457                                 }
2458                             } catch(E) {
2459                                 alert('error in oncomplete: ' + E);
2460                             }
2461                         }
2462                     }
2463                 );
2464             }
2465         );
2466     }
2467 }