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