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