]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/invoice/view.js
LP#1351317 ACQ fund selector filters cont.
[working/Evergreen.git] / Open-ILS / web / js / ui / default / acq / invoice / view.js
1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dojo.cookie');
4 dojo.require('dijit.form.CheckBox');
5 dojo.require('dijit.form.Button');
6 dojo.require('dijit.form.CurrencyTextBox');
7 dojo.require('dijit.form.NumberTextBox');
8 dojo.require('openils.User');
9 dojo.require('openils.Util');
10 dojo.require('openils.CGI');
11 dojo.require('openils.PermaCrud');
12 dojo.require('openils.widget.EditPane');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('openils.widget.ProgressDialog');
15 dojo.require('openils.acq.Lineitem');
16 dojo.require('openils.XUL');
17
18 dojo.requireLocalization('openils.acq', 'acq');
19 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
20
21 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
22 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
23 var fundSearchFilter = {}; 
24
25 var cgi = new openils.CGI();
26 var pcrud = new openils.PermaCrud();
27 var attachLi;
28 var attachPo;
29 var invoice;
30 var itemTbody;
31 var itemTemplate;
32 var entryTemplate;
33 var totalInvoicedBox;
34 var totalPaidBox;
35 var balanceOwedBox;
36 var invoicePane;
37 var itemTypes;
38 var virtualId = -1;
39 var extraCopies = {};
40 var extraCopiesFund;
41 var widgetRegistry = {acqie : {}, acqii : {}};
42 var focusLineitem;
43 var searchInitDone = false;
44 var termManager;
45 var resultManager;
46
47 function nodeByName(name, context) {
48     return dojo.query('[name='+name+']', context)[0];
49 }
50
51 function init() {
52     // before rendering any fund selectors, limit the funds to 
53     // attempt to retrieve to those the user can actually use.
54     new openils.User().getPermOrgList(
55         ['ADMIN_INVOICE','CREATE_INVOICE','MANAGE_FUND'],
56         function(orgs) { 
57             fundSearchFilter.org = orgs;
58             init2();
59         },
60         true, true // descendants, id_list
61     );
62 }
63
64 function init2() {
65
66     attachLi = cgi.param('attach_li') || [];
67     if (!dojo.isArray(attachLi)) 
68         attachLi = [attachLi];
69
70     attachPo = cgi.param('attach_po') || [];
71     if (!dojo.isArray(attachPo)) 
72         attachPo = [attachPo];
73
74     focusLineitem = new openils.CGI().param('focus_li');
75
76     totalInvoicedBox = dojo.byId('acq-total-invoiced-box');
77     totalPaidBox = dojo.byId('acq-total-paid-box');
78     balanceOwedBox = dojo.byId('acq-total-balance-box');
79
80     itemTypes = pcrud.retrieveAll('aiit');
81
82     dojo.byId('acq-invoice-summary-toggle-off').onclick = function() {
83         openils.Util.hide(dojo.byId('acq-invoice-summary'));
84         openils.Util.show(dojo.byId('acq-invoice-summary-small'));
85     };
86
87     dojo.byId('acq-invoice-summary-toggle-on').onclick = function() {
88         openils.Util.show(dojo.byId('acq-invoice-summary'));
89         openils.Util.hide(dojo.byId('acq-invoice-summary-small'));
90     }
91
92     if(cgi.param('create')) {
93         renderInvoice();
94
95         // show summary info by default for new invoices
96         dojo.byId('acq-invoice-summary-toggle-on').onclick();
97
98     } else {
99         dojo.byId('acq-invoice-summary-toggle-off').onclick();
100         fieldmapper.standardRequest(
101             ['open-ils.acq', 'open-ils.acq.invoice.retrieve.authoritative'],
102             {
103                 params : [openils.User.authtoken, invoiceId],
104                 oncomplete : function(r) {
105                     invoice = openils.Util.readResponse(r);     
106                     renderInvoice();
107                 }
108             }
109         );
110     }
111
112     extraCopiesFund = new openils.widget.AutoFieldWidget({
113         fmField : 'fund',
114         fmClass : 'acqlid',
115         searchFilter : {active : 't'},
116         labelFormat : fundLabelFormat,
117         searchFormat : fundSearchFormat,
118         searchFilter : fundSearchFilter,
119         dijitArgs : {required : true},
120         parentNode : dojo.byId('acq-invoice-extra-copies-fund')
121     });
122     extraCopiesFund.build();
123 }
124
125 function renderInvoice() {
126
127     // in create mode, let the LI or PO render the invoice with seed data
128     if( !(cgi.param('create') && (attachPo.length || attachLi.length)) ) {
129         invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), invoice);
130     }
131
132     dojo.byId('acq-invoice-new-item').onclick = function() {
133         var item = new fieldmapper.acqii();
134         item.id(virtualId--);
135         item.isnew(true);
136         addInvoiceItem(item);
137     }
138
139     updateTotalCost();
140
141     if(invoice && openils.Util.isTrue(invoice.complete())) {
142
143         dojo.forEach( // hide widgets that should not be visible for a completed invoice
144             dojo.query('.hide-complete'), 
145             function(node) { openils.Util.hide(node); }
146         );
147
148         new openils.User().getPermOrgList(
149             'ACQ_INVOICE_REOPEN', 
150             function (orgs) {
151                 if(orgs.indexOf(invoice.receiver()) >= 0)
152                     openils.Util.show('acq-invoice-reopen-button-wrapper', 'inline');
153             }, 
154             true, 
155             true
156         );
157     }
158
159     // display items and entries in ID order 
160     // which effectively equates to add order.
161     function idsort(a, b) { return a.id() < b.id() ? -1 : 1 }
162
163     if(invoice) {
164         dojo.forEach(
165             invoice.items().sort(idsort),
166             function(item) {
167                 addInvoiceItem(item);
168             }
169         );
170
171         dojo.forEach(
172             invoice.entries().sort(idsort),
173             function(entry) {
174                 addInvoiceEntry(entry);
175             }
176         );
177     }
178
179     if(attachLi.length) doAttachLi();
180     if(attachPo.length) doAttachPo(0);
181 }
182
183 function doAttachLi(skipInit) {
184
185     //var invoiceArgs = {provider : lineitem.provider(), shipper : lineitem.provider()}; 
186     if(cgi.param('create') && !skipInit) {
187
188         // use the first LI in the list to determine the default provider
189         fieldmapper.standardRequest(
190             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
191             {
192                 params : [openils.User.authtoken, attachLi[0], {clear_marc:1}],
193                 oncomplete : function(r) {
194                     var li = openils.Util.readResponse(r);
195                     invoicePane = drawInvoicePane(
196                         dojo.byId('acq-view-invoice-div'), null, 
197                         {provider : li.provider(), shipper : li.provider()}
198                     );
199                 }
200             }
201         );
202     }
203
204     dojo.forEach(attachLi,
205         function(li) {
206             var entry = new fieldmapper.acqie();
207             entry.id(virtualId--);
208             entry.isnew(true);
209             entry.lineitem(li);
210             addInvoiceEntry(entry);
211         }
212     );
213 }
214
215 function doAttachPo(idx) {
216
217     if (idx == attachPo.length) return;
218     var poId = attachPo[idx];
219
220     fieldmapper.standardRequest(
221         ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
222         {   async: true,
223             params: [
224                 openils.User.authtoken, poId,
225                 {flesh_lineitem_ids : true, flesh_po_items : true}
226             ],
227             oncomplete: function(r) {
228                 var po = openils.Util.readResponse(r);
229
230                 if(cgi.param('create') && idx == 0) {
231                     // render the invoice using some seed data from the first PO
232                     var invoiceArgs = {provider : po.provider(), shipper : po.provider()}; 
233                     invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), null, invoiceArgs);
234                 }
235
236                 dojo.forEach(po.lineitems(), 
237                     function(lineitem) {
238                         var entry = new fieldmapper.acqie();
239                         entry.id(virtualId--);
240                         entry.isnew(true);
241                         entry.lineitem(lineitem);
242                         entry.purchase_order(po);
243                         addInvoiceEntry(entry);
244                     }
245                 );
246
247                 dojo.forEach(po.po_items(),
248                     function(poItem) {
249                         var item = new fieldmapper.acqii();
250                         item.id(virtualId--);
251                         item.isnew(true);
252                         item.fund(poItem.fund());
253                         item.title(poItem.title());
254                         item.author(poItem.author());
255                         item.note(poItem.note());
256                         item.inv_item_type(poItem.inv_item_type());
257                         item.purchase_order(po);
258                         item.po_item(poItem);
259                         addInvoiceItem(item);
260                     }
261                 );
262
263                 doAttachPo(++idx);
264             }
265         }
266     );
267 }
268
269 // XUL cookie bits
270 var cookieUriSSL, cookieSvc, cookieMgr;
271
272 function performSearch(pageDir, clearFirst) {
273     if (clearFirst)
274         clearSearchResTable(); 
275
276     var searchObject = termManager.buildSearchObject();
277
278     if (openils.XUL.isXUL()) {
279
280         cookieSvc.setCookieString(cookieUriSSL, null, 
281             "invs=" + base64Encode(searchObject) + ';max-age=2592000', null);
282
283         cookieSvc.setCookieString(cookieUriSSL, null, 
284             "invc=" + dojo.byId("acq-unified-conjunction").getValue() + 
285                 ';max-age=2592000', null);
286
287     } else {
288
289         dojo.cookie('invs', base64Encode(searchObject));
290         dojo.cookie('invc', dojo.byId("acq-unified-conjunction").getValue());
291     }
292
293     if (pageDir == 0) { // new search
294         resultsLoader.displayOffset = 0;
295     } else {
296         resultsLoader.displayOffset += pageDir * resultsLoader.displayLimit;
297     }
298
299     if (resultsLoader.displayOffset == 0) {
300         openils.Util.hide('acq-inv-search-prev');
301     } else {
302         openils.Util.show('acq-inv-search-prev', 'inline');
303     }
304
305     if (dojo.byId('acq-invoice-search-limit-invoiceable').checked) {
306         if (!searchObject.jub) 
307             searchObject.jub = [];
308
309         // exclude lineitems that are "cancelled" (sidebar: 'Mericans spell it 'canceled')
310         searchObject.jub.push({state : 'cancelled', '__not' : true});
311
312         // exclude lineitems already linked to this invoice
313         if (invoice && invoice.id() > 0) { 
314             if (!searchObject.acqinv)
315                 searchObject.acqinv = [];
316             searchObject.acqinv.push({id : invoice.id(), '__not' : true});
317         }
318
319         // limit to lineitems that have invoiceable copies
320         searchObject.acqlisumi = [{item_count : 1, '_gte' : true}];
321
322         // limit to provider if a provider is selected
323         var provider = invoicePane.getFieldValue('provider');
324         if (provider) {
325             if (!searchObject.jub.filter(function(i) { return i.provider != null }).length)
326                 searchObject.jub.push({provider : provider});
327         }
328     }
329
330     if (dojo.byId('acq-invoice-search-sort-title').checked) {
331         uriManager.order_by = 
332             [ {"class": "acqlia", "field":"attr_value", "transform":"first"} ];
333     }
334
335     resultsLoader.lastSearch = searchObject;
336     resultManager.go(searchObject)
337     console.log('Lineitem Search: ' + js2JSON(searchObject));
338     focusLastSearchInput();
339 }
340
341
342 function renderUnifiedSearch() {
343
344     if (!searchInitDone) {
345
346         searchInitDone = true;
347         termManager = new TermManager();
348         resultManager = new ResultManager();
349         resultsLoader = new searchResultsLoader();
350         uriManager = new URIManager();
351
352         // define custom lineitem result handler
353         resultManager.result_types = {
354             "lineitem": {
355                 "search_options": { "id_list": true },
356                 "revealer": function() { },
357                 "finisher": function() {
358                     resultsLoader.batch_length = resultManager.count_results;
359                 },
360                 "adder": function(li) {
361                     resultsLoader.addLineitem(li);
362                 },
363                 "interface": resultsLoader
364             },
365             "no_results": {
366                 "revealer": function() { }
367             }
368
369         };
370
371         resultManager.no_results_popup = true;
372         resultManager.submitter = smartSearchSubmitter;
373
374         var searchObject, searchConjunction;
375
376         if (openils.XUL.isXUL()) {
377     
378             if (!cookieSvc) {
379
380                 var ios = Components.classes["@mozilla.org/network/io-service;1"]
381                     .getService(Components.interfaces.nsIIOService);
382
383                 cookieUriSSL = ios.newURI("https://" + location.hostname, null, null);
384     
385                 cookieSvc = Components.classes["@mozilla.org/cookieService;1"]
386                     .getService(Components.interfaces.nsICookieService);
387
388
389                 cookieManager = Components.classes["@mozilla.org/cookiemanager;1"]
390                     .getService(Components.interfaces.nsICookieManager);
391             }
392
393             var iter = cookieManager.enumerator;
394             while (iter.hasMoreElements()) {
395                 var cookie = iter.getNext();
396                 if (cookie instanceof Components.interfaces.nsICookie) {
397                     if (cookie.name == 'invs')
398                         searchObject = cookie.value;
399                     if (cookie.name == 'invc')
400                         searchConjunction = cookie.value;
401                 }
402             }
403
404         } else {
405             // useful for web-based testing
406             searchObject = dojo.cookie('invs');
407             searchConjunction = dojo.cookie('invc');
408         }
409
410         if (searchObject) {
411
412             // if there is a search object cookie, populate the search form
413             termManager.reflect(base64Decode(searchObject));
414             dojo.byId("acq-unified-conjunction").setValue(searchConjunction);
415
416         } else {
417             console.log('adding row');
418             termManager.addRow();
419         }
420     }
421
422     dojo.addClass(dojo.byId('oils-acq-invoice-table'), 'hidden');
423     dojo.removeClass(dojo.byId('oils-acq-invoice-search'), 'hidden');
424     focusLastSearchInput();
425 }
426
427 function focusLastSearchInput() {
428     // TODO: see about making this better and moving it into search/unified.js
429     var wnodes = dojo.query('[name=widget]');
430     var inputNode = wnodes.item(wnodes.length - 1).firstChild;
431     if (inputNode) {
432         try {
433             inputNode.select();
434         } catch(E) {
435             inputNode.focus();
436         }
437     }
438 }
439
440 var resultsTbody, resultsRow;
441 function searchResultsLoader() {
442     this.displayOffset = 0;
443     this.displayLimit = 10;
444
445     if (!resultsTbody) {
446         resultsTbody = dojo.byId('acq-invoice-search-results-tbody');
447         resultsRow = resultsTbody.removeChild(dojo.byId('acq-invoice-search-results-tr'));
448     }
449
450     this.addLineitem = function(li_id) {
451         console.log('Adding search result lineitem ' + li_id);
452         var row = resultsRow.cloneNode(true);
453         resultsTbody.appendChild(row);
454         var checkbox = dojo.query('[name=search-results-checkbox]', row)[0];
455         checkbox.setAttribute('lineitem', li_id);
456
457         // this lineitem is already part of the invoice
458         if (dojo.query('[entry_lineitem_row=' + li_id + ']')[0]) {
459             checkbox.disabled = true;
460             dojo.addClass(checkbox.parentNode, 'search-results-already-invoiced');
461         }
462
463         openils.acq.Lineitem.fetchAndRender(
464             li_id, {}, 
465             function(li, html) { 
466                 dojo.query('[name=search-results-content-div]', row)[0].innerHTML = html;
467             }
468         );
469     }
470 }
471
472 function addSelectedToInvoice() {
473     var inputs = dojo.query('[name=search-results-checkbox]');
474     attachLi = [];
475     dojo.forEach(inputs,
476         function(checkbox) {
477             if (checkbox.checked) {
478                 attachLi.push(checkbox.getAttribute('lineitem'));
479                 checkbox.disabled = true;
480                 checkbox.checked = false;
481                 dojo.addClass(checkbox.parentNode, 'search-results-already-invoiced');
482             }
483         }
484     );
485     doAttachLi(true);
486 }
487
488 allResSelected = false;
489 function clearSearchResTable() {
490     allResSelected = false;
491     while (resultsTbody.childNodes[0])
492         resultsTbody.removeChild(resultsTbody.childNodes[0]);
493 }
494
495 function selectSearchResults() {
496     allResSelected = !allResSelected;
497     dojo.query('[name=search-results-checkbox]').forEach(
498         function(input) { input.checked = allResSelected });
499 }
500
501 function updateTotalCost() {
502
503     var totalCost = 0;    
504     for(var id in widgetRegistry.acqii) 
505         if(!widgetRegistry.acqii[id]._object.isdeleted())
506             totalCost += Number(widgetRegistry.acqii[id].cost_billed.getFormattedValue());
507     for(var id in widgetRegistry.acqie) 
508         if(!widgetRegistry.acqie[id]._object.isdeleted())
509             totalCost += Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue());
510     totalInvoicedBox.innerHTML = totalCost.toFixed(2);
511
512     totalPaid = 0;    
513     for(var id in widgetRegistry.acqii) 
514         if(!widgetRegistry.acqii[id]._object.isdeleted())
515             totalPaid += Number(widgetRegistry.acqii[id].amount_paid.getFormattedValue());
516     for(var id in widgetRegistry.acqie) 
517         if(!widgetRegistry.acqie[id]._object.isdeleted())
518             totalPaid += Number(widgetRegistry.acqie[id].amount_paid.getFormattedValue());
519     totalPaidBox.innerHTML = totalPaid.toFixed(2);
520
521     var buttonsDisabled = false;
522
523     if(totalPaid > totalCost || totalPaid < 0) {
524         openils.Util.addCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
525         invoiceSaveButton.attr('disabled', true);
526         invoiceProrateButton.attr('disabled', true);
527         buttonsDisabled = true;
528     } else {
529         openils.Util.removeCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
530         invoiceSaveButton.attr('disabled', false);
531         invoiceProrateButton.attr('disabled', false);
532     }
533
534     if(totalCost < 0) {
535         openils.Util.addCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
536         invoiceSaveButton.attr('disabled', true);
537         invoiceProrateButton.attr('disabled', true);
538     } else {
539         openils.Util.removeCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
540         if(!buttonsDisabled) {
541             invoiceSaveButton.attr('disabled', false);
542             invoiceProrateButton.attr('disabled', false);
543         }
544     }
545
546     if(totalPaid == totalCost) { // XXX: too rigid?
547         invoiceCloseButton.attr('disabled', false);
548     } else {
549         invoiceCloseButton.attr('disabled', true);
550     }
551
552     balanceOwedBox.innerHTML = (totalCost - totalPaid).toFixed(2);
553
554     updateExpectedCost();
555 }
556
557
558 function registerWidget(obj, field, widget, callback) {
559     var blob = widgetRegistry[obj.classname];
560     if(!blob[obj.id()]) 
561         blob[obj.id()] = {_object : obj};
562     blob[obj.id()][field] = widget;
563     widget.build(
564         function(w, ww) {
565             dojo.connect(w, 'onChange', 
566                 function(newVal) { 
567                     obj.ischanged(true); 
568                     updateTotalCost();
569                 }
570             );
571             if(callback) callback(w, ww);
572         }
573     );
574     return widget;
575 }
576
577 function addInvoiceItem(item) {
578     itemTbody = dojo.byId('acq-invoice-item-tbody');
579     if(itemTemplate == null) {
580         itemTemplate = itemTbody.removeChild(dojo.byId('acq-invoice-item-template'));
581     }
582
583     var row = itemTemplate.cloneNode(true);
584     var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
585
586     dojo.forEach(
587         ['title', 'author', 'cost_billed', 'amount_paid'], 
588         function(field) {
589             
590             var args;
591             if(field == 'title' || field == 'author') {
592                 //args = {style : 'width:10em'};
593             } else if(field == 'cost_billed' || field == 'amount_paid') {
594                 args = {required : true, style : 'width: 8em'};
595             }
596
597             registerWidget(
598                 item,
599                 field,
600                 new openils.widget.AutoFieldWidget({
601                     fmClass : 'acqii',
602                     fmObject : item,
603                     fmField : field,
604                     readOnly : invoice && openils.Util.isTrue(invoice.complete()),
605                     dijitArgs : args,
606                     parentNode : nodeByName(field, row)
607                 }),
608                 function(w) {
609                     if (field == "cost_billed") {
610                         dojo.connect(
611                             w, "onChange", function(value) {
612                                 var paid = widgetRegistry.acqii[item.id()].amount_paid.widget;
613                                 if (value && isNaN(paid.attr("value")))
614                                     paid.attr("value", value);
615                             }
616                         );
617                     }
618                 }
619             );
620         }
621     );
622
623
624     /* ----------- fund -------------- */
625     var fundArgs = {
626         fmClass : 'acqii',
627         fmObject : item,
628         fmField : 'fund',
629         labelFormat : fundLabelFormat,
630         searchFormat : fundSearchFormat,
631         searchFilter : fundSearchFilter,
632         readOnly : invoice && openils.Util.isTrue(invoice.complete()),
633         dijitArgs : {required : true},
634         parentNode : nodeByName('fund', row)
635     }
636
637     if(item.fund_debit()) {
638         fundArgs.searchFilter = {'-or' : [{active : 't'}, {id : item.fund()}]};
639     } else {
640         fundArgs.searchFilter = {active : 't'}
641         if(itemType && openils.Util.isTrue(itemType.prorate()))
642             fundArgs.dijitArgs = {disabled : true};
643     }
644
645     var fundWidget = new openils.widget.AutoFieldWidget(fundArgs);
646     registerWidget(item, 'fund', fundWidget);
647
648     /* ---------- inv_item_type ------------- */
649
650     if(item.po_item()) {
651
652         // read-only item view for items that were the result of a po-item
653         var po = item.purchase_order();
654         var po_item = item.po_item();
655         var node = nodeByName('inv_item_type', row);
656         var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
657         orderDate = (!po.order_date()) ? '' : 
658                 dojo.date.locale.format(dojo.date.stamp.fromISOString(po.order_date()), {selector:'date'});
659
660         node.innerHTML = dojo.string.substitute(
661             localeStrings.INVOICE_ITEM_PO_DETAILS, 
662             [ 
663                 itemType.name(),
664                 oilsBasePath, 
665                 po.id(), 
666                 po.name(), 
667                 orderDate,
668                 po_item.estimated_cost() 
669             ]
670         );
671
672     } else {
673
674         registerWidget(
675             item,
676             'inv_item_type',
677             new openils.widget.AutoFieldWidget({
678                 fmObject : item,
679                 fmField : 'inv_item_type',
680                 parentNode : nodeByName('inv_item_type', row),
681                 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
682                 dijitArgs : {required : true}
683             }),
684             function(w, ww) {
685                 // When the inv_item_type is set to prorate=true, don't allow the user the edit the fund
686                 // since this charge will be prorated against (potentially) multiple funds
687                 dojo.connect(w, 'onChange', 
688                     function() {
689                         if(!item.fund_debit()) {
690                             var itemType = itemTypes.filter(function(t) { return (t.code() == w.attr('value')) })[0];
691                             if(!itemType) return;
692                             if(openils.Util.isTrue(itemType.prorate())) {
693                                 fundWidget.widget.attr('disabled', true);
694                                 fundWidget.widget.attr('value', '');
695                             } else {
696                                 fundWidget.widget.attr('disabled', false);
697                             }
698                         }
699                     }
700                 );
701             }
702         );
703     }
704
705     nodeByName('delete', row).onclick = function() {
706         var cost = widgetRegistry.acqii[item.id()].cost_billed.getFormattedValue();
707         var msg = dojo.string.substitute(
708             localeStrings.INVOICE_CONFIRM_ITEM_DELETE, [
709                 cost || 0,
710                 widgetRegistry.acqii[item.id()].inv_item_type.getFormattedValue() || ''
711             ]
712         );
713         if(!confirm(msg)) return;
714         itemTbody.removeChild(row);
715         item.isdeleted(true);
716         if(item.isnew())
717             delete widgetRegistry.acqii[item.id()];
718         updateTotalCost();
719     }
720
721     itemTbody.appendChild(row);
722     updateTotalCost();
723 }
724
725 function updateReceiveLink(li) {
726     if (!invoiceId)
727         return; /* can't do this with unsaved invoices */
728
729     var link = dojo.byId("acq-view-invoice-receive-link");
730     if (link.onclick) return; /* only need to do this once */
731
732     /* don't do this if there's nothing receivable on the lineitem */
733     if (li.order_summary().recv_count() + li.order_summary().cancel_count() >=
734         li.order_summary().item_count())
735         return;
736
737     openils.Util.show("acq-view-invoice-receive");
738     link.onclick = function() { location.href =  oilsBasePath + '/acq/invoice/receive/' + invoiceId; };
739 }
740
741 /*
742  * Ensures focusLineitem is in view and causes a brief 
743  * border around the lineitem to come to life then fade.
744  */
745 function focusLi() {
746     if (!focusLineitem) return;
747
748     // set during addLineitem()
749     var node = dojo.byId('li-title-ref-' + focusLineitem);
750
751     console.log('focus: li-title-ref-' + focusLineitem + ' : ' + node);
752
753     // LI may not yet be rendered
754     if (!node) return; 
755
756     console.log('focusing ' + focusLineitem);
757
758     // prevent numerous re-focuses
759     focusLineitem = null; 
760
761     // causes the full row to be visible
762     dijit.scrollIntoView(node);
763
764     dojo.require('dojox.fx');
765
766     setTimeout(
767         function() {
768             dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
769         }, 
770     100);
771 }
772
773
774 // expected cost is totalCostInvoiced + totalCostNotYetInvoiced
775 function updateExpectedCost() {
776
777     var cost = Number(totalInvoicedBox.innerHTML || 0);
778
779     // for any LI's that are not yet billed (i.e. filled in)
780     // use the total expected cost for that lineitem.
781     for(var id in widgetRegistry.acqie) {
782         var entry = widgetRegistry.acqie[id]._object;
783         if(!entry.isdeleted()) {
784             if (Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue()) == 0) {
785                 var li = entry.lineitem();
786                 cost += 
787                     Number(li.order_summary().estimated_amount()) - 
788                     Number(li.order_summary().paid_amount());
789             }
790         }
791     }
792
793     dojo.byId('acq-invoice-summary-cost').innerHTML = cost.toFixed(2);
794 }
795
796 var invoicEntryWidgets = {};
797 function addInvoiceEntry(entry) {
798     console.log('Adding new entry for lineitem ' + entry.lineitem());
799
800     openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-header'), 'hidden');
801     openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-thead'), 'hidden');
802     openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-tbody'), 'hidden');
803
804     dojo.byId('acq-invoice-summary-count').innerHTML = 
805         Number(dojo.byId('acq-invoice-summary-count').innerHTML) + 1;
806
807     entryTbody = dojo.byId('acq-invoice-entry-tbody');
808     if(entryTemplate == null) {
809         entryTemplate = entryTbody.removeChild(dojo.byId('acq-invoice-entry-template'));
810     }
811
812     if(dojo.query('[lineitem=' + entry.lineitem() +']', entryTbody)[0])
813         // Is it ever valid to have multiple entries for 1 lineitem in a single invoice?
814         return;
815
816     var row = entryTemplate.cloneNode(true);
817     row.setAttribute('lineitem', entry.lineitem());
818     row.setAttribute('entry_lineitem_row', entry.lineitem());
819
820     openils.acq.Lineitem.fetchAndRender(
821         entry.lineitem(), {}, 
822         function(li, html) { 
823             entry.lineitem(li);
824             entry.purchase_order(li.purchase_order());
825             nodeByName('title_details', row).innerHTML = html;
826
827             nodeByName('title_details', row).parentNode.id = 'li-title-ref-' + li.id();
828             console.log(dojo.byId('li-title-ref-' + li.id()));
829
830             updateReceiveLink(li);
831
832             // set some default values if otherwise unset
833             if (!invoicePane.getFieldValue('receiver')) {
834                 invoicePane.setFieldValue('receiver', li.purchase_order().ordering_agency());
835             }
836             if (!invoicePane.getFieldValue('provider')) {
837                 invoicePane.setFieldValue('provider', li.purchase_order().provider());
838             }
839
840             dojo.forEach(
841                 ['inv_item_count', 'phys_item_count', 'cost_billed', 'amount_paid'],
842                 function(field) {
843                     var dijitArgs = {required : true, constraints : {min: 0}, style : 'width:6em'};
844                     if(field.match(/count/)) {
845                         dijitArgs.style = 'width:4em;';
846                     } else {
847                         dijitArgs.style = 'width:9em;';
848                     }
849                     if (entry.isnew() && (field == 'phys_item_count' || field == 'inv_item_count')) {
850                         // by default, attempt to pay for all non-canceled and as-of-yet-un-invoiced items
851                         var count = Number(li.order_summary().item_count() || 0) - 
852                                     Number(li.order_summary().cancel_count() || 0) -
853                                     Number(li.order_summary().invoice_count() || 0);
854                         if(count < 0) count = 0;
855                         dijitArgs.value = count;
856                     }
857                     registerWidget(
858                         entry, 
859                         field,
860                         new openils.widget.AutoFieldWidget({
861                             fmObject : entry,
862                             fmClass : 'acqie',
863                             fmField : field,
864                             dijitArgs : dijitArgs,
865                             readOnly : invoice && openils.Util.isTrue(invoice.complete()),
866                             parentNode : nodeByName(field, row)
867                         }),
868                         function(w) {    
869
870                             if(field == 'phys_item_count') {
871                                 dojo.connect(w, 'onChange', 
872                                     function() {
873                                         // staff entered a higher number in the receive field than was originally ordered
874                                         // taking into account already invoiced items
875                                         var extra = Number(this.attr('value')) - 
876                                             (Number(entry.lineitem().item_count()) - Number(entry.lineitem().order_summary().invoice_count()));
877                                         if(extra > 0) {
878                                             storeExtraCopies(entry, extra);
879                                         }
880                                     }
881                                 )
882                             } // if
883
884                             if (field == "cost_billed") {
885                                 // hooks applied with dojo.connect to dijit events are additive, so there's no conflict between this and what comes next
886                                 dojo.connect(
887                                     w, "onChange", function(value) {
888                                     var paid = widgetRegistry.acqie[entry.id()].amount_paid.widget;
889                                         if (value && isNaN(paid.attr("value")))
890                                             paid.attr("value", value);
891                                     }
892                                 );
893                             }
894                             if(field == 'inv_item_count' || field == 'cost_billed') {
895                                 setPerCopyPrice(row, entry);
896                                 // update the per-copy count as invoice count and cost billed change 
897                                 dojo.connect(w, 'onChange', function() { setPerCopyPrice(row, entry) } );
898                             } 
899
900                         } // func
901                     );
902                 }
903             );
904
905             updateTotalCost();
906             if (focusLineitem == li.id())
907                 focusLi();
908         }
909     );
910
911     nodeByName('detach', row).onclick = function() {
912         var cost = widgetRegistry.acqie[entry.id()].cost_billed.getFormattedValue();
913         var idents = [];
914         dojo.forEach(['isbn', 'upc', 'issn'], 
915             function(ident) { 
916                 var val = liMarcAttr(entry.lineitem(), ident);
917                 if(val) idents.push(val); 
918             }
919         );
920
921         var msg = dojo.string.substitute(
922             localeStrings.INVOICE_CONFIRM_ENTRY_DETACH, [
923                 cost || 0,
924                 liMarcAttr(entry.lineitem(), 'title'),
925                 liMarcAttr(entry.lineitem(), 'author'),
926                 idents.join(',')
927             ]
928         );
929         if(!confirm(msg)) return;
930         entryTbody.removeChild(row);
931         entry.isdeleted(true);
932         if(entry.isnew())
933             delete widgetRegistry.acqie[entry.id()];
934         updateTotalCost();
935     }
936
937     entryTbody.appendChild(row);
938 }
939
940 function setPerCopyPrice(row, entry) {
941     var inv_w = widgetRegistry.acqie[entry.id()].inv_item_count;
942     var bill_w = widgetRegistry.acqie[entry.id()].cost_billed;
943
944     if (inv_w && bill_w) {
945         var invoiced = Number(inv_w.getFormattedValue());
946         var billed = Number(bill_w.getFormattedValue());
947         console.log(invoiced + ' : ' + billed);
948         if (invoiced > 0) {
949             nodeByName('amount_paid_per_copy', row).innerHTML = (billed / invoiced).toFixed(2);
950         } else {
951             nodeByName('amount_paid_per_copy', row).innerHTML = '0.00';
952         }
953     }
954 }
955
956 function liMarcAttr(lineitem, name) {
957     var attr = lineitem.attributes().filter(
958         function(attr) { 
959             if(
960                 attr.attr_type() == 'lineitem_marc_attr_definition' && 
961                 attr.attr_name() == name) 
962                     return attr 
963         } 
964     )[0];
965     return (attr) ? attr.attr_value() : '';
966 }
967
968 function saveChanges(args) {
969     args = args || {};
970     createExtraCopies(function() { saveChangesPartTwo(args); });
971 }
972
973 // Define a helper function to 'unflesh' sub-objects from an fmclass object.
974 // 'this' specifies the object; the arguments specify a list of names of
975 // sub-objects.
976 function unflesh() {
977     var _, $ = this;
978     dojo.forEach(arguments, function (n) {
979         _ = $[n]();
980         if (_ !== null && typeof _ === 'object')
981             $[n]( _.id() );
982     });
983 }
984
985 function saveChangesPartTwo(args) {
986     args = args || {};
987
988     if(args.reopen) {
989         invoice.complete('f');
990
991     } else {
992
993         // Prepare an invoice for submission
994         if(!invoice) {
995             invoice = new fieldmapper.acqinv();
996             invoice.isnew(true);
997         } else {
998             invoice.ischanged(true); // for now, just always update
999         }
1000
1001         var e = invoicePane.mapValues(function (n, v) { invoice[n](v); });
1002         if (e instanceof Error) {
1003             alert(e.message);
1004             return;
1005         }
1006
1007         if(args.close)
1008             invoice.complete('t');
1009
1010
1011         // Prepare any charge items
1012         var updateItems = [];
1013         for(var id in widgetRegistry.acqii) {
1014             var reg = widgetRegistry.acqii[id];
1015             var item = reg._object;
1016             if(item.ischanged() || item.isnew() || item.isdeleted()) {
1017                 updateItems.push(item);
1018                 if(item.isnew()) item.id(null);
1019                 for(var field in reg) {
1020                     if(field != '_object')
1021                         item[field]( reg[field].getFormattedValue() );
1022                 }
1023                 
1024                 unflesh.call(item, 'purchase_order');
1025
1026             }
1027         }
1028
1029         // Prepare any line items
1030         var updateEntries = [];
1031         for(var id in widgetRegistry.acqie) {
1032             var reg = widgetRegistry.acqie[id];
1033             var entry = reg._object;
1034             if(entry.ischanged() || entry.isnew() || entry.isdeleted()) {
1035                 updateEntries.push(entry);
1036                 if(entry.isnew()) entry.id(null);
1037
1038                 for(var field in reg) {
1039                     if(field != '_object')
1040                         entry[field]( reg[field].getFormattedValue() );
1041                 }
1042                 
1043                 unflesh.call(entry, 'purchase_order', 'lineitem');
1044             }
1045         }
1046     }
1047
1048     progressDialog.show(true);
1049     fieldmapper.standardRequest(
1050         ['open-ils.acq', 'open-ils.acq.invoice.update'],
1051         {
1052             params : [openils.User.authtoken, invoice, updateEntries, updateItems],
1053             oncomplete : function(r) {
1054                 progressDialog.hide();
1055                 var invoice = openils.Util.readResponse(r);
1056                 if(invoice) {
1057                     if(args.prorate)
1058                         return prorateInvoice(invoice);
1059                     if (args.clear) {
1060                         location.href = oilsBasePath + '/acq/invoice/view?create=1';
1061                     } else {
1062                         location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
1063                     }
1064                 }
1065             }
1066         }
1067     );
1068 }
1069
1070 function prorateInvoice(invoice) {
1071     if(!confirm(localeStrings.INVOICE_CONFIRM_PRORATE)) return;
1072     progressDialog.show(true);
1073
1074     fieldmapper.standardRequest(
1075         ['open-ils.acq', 'open-ils.acq.invoice.apply_prorate'],
1076         {
1077             params : [openils.User.authtoken, invoice.id()],
1078             oncomplete : function(r) {
1079                 progressDialog.hide();
1080                 var invoice = openils.Util.readResponse(r);
1081                 if(invoice) {
1082                     location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
1083                 }
1084             }
1085         }
1086     );
1087 }
1088
1089 function storeExtraCopies(entry, numExtra) {
1090
1091     dojo.byId('acq-invoice-extra-copies-message').innerHTML = 
1092         dojo.string.substitute(
1093             localeStrings.INVOICE_EXTRA_COPIES, [numExtra]);
1094
1095     var addCopyHandler;
1096     addCopyHandler = dojo.connect(
1097         extraCopiesGo, 
1098         'onClick',
1099         function() {
1100             extraCopies[entry.lineitem().id()] = {
1101                 numExtra : numExtra, 
1102                 fund : extraCopiesFund.widget.attr('value')
1103             }
1104             extraItemsDialog.hide();
1105             dojo.disconnect(addCopyHandler);
1106         }
1107     );
1108
1109     dojo.connect(
1110         extraCopiesCancel, 
1111         'onClick',
1112         function() { 
1113             widgetRegistry.acqie[entry.id()].phys_item_count.widget.attr('value', '');
1114             extraItemsDialog.hide() 
1115         }
1116     );
1117
1118     extraItemsDialog.show();
1119 }
1120
1121 function validateInvIdent(inv_ident, provider, receiver) {
1122     if (!(inv_ident && provider && receiver)) {
1123         console.info("not enough information to pre-validate inv_ident");
1124         return;
1125     }
1126
1127     openils.Util.show("ident-validation-spinner", "inline");
1128     var pcrud = new openils.PermaCrud();
1129     pcrud.search(
1130         "acqinv", {"inv_ident": inv_ident, "provider": provider}, {
1131             "oncomplete": function(r) {
1132                 openils.Util.hide("ident-validation-spinner");
1133
1134                 /* This could throw an event about the user not having perms,
1135                  * but in such a case the whole interface is already busted
1136                  * anyway. */
1137                 r = openils.Util.readResponse(r);
1138
1139                 var w = invoicePane.getFieldWidget("inv_ident").widget;
1140                 if (r.length) {
1141                     alert(localeStrings.INVOICE_IDENT_COLLIDE);
1142                     w.validator = function() { return false; };
1143                     w.validate();
1144                 } else {
1145                     w.validator = function() { return true; };
1146                     w.validate();
1147                 }
1148                 w.focus();
1149                 pcrud.disconnect();
1150             }
1151         }
1152     );
1153 }
1154
1155 function drawInvoicePane(parentNode, inv, args) {
1156     args = args || {};
1157     var pane;
1158
1159     var override = {};
1160     if(!inv) {
1161         override = {
1162             recv_date : {widgetValue : dojo.date.stamp.toISOString(new Date())},
1163             //receiver : {widgetValue : openils.User.user.ws_ou()},
1164             receiver : {
1165                 "dijitArgs": {
1166                     "onChange": function(val) {
1167                         validateInvIdent(
1168                             invoicePane && invoicePane.getFieldValue("inv_ident"),
1169                             invoicePane && invoicePane.getFieldValue("provider"),
1170                             val
1171                         );
1172                     }
1173                 }
1174             },
1175             recv_method : {widgetValue : 'PPR'}
1176         };
1177     }
1178
1179     dojo.mixin(override, {
1180         provider : { 
1181             dijitArgs : { 
1182                 store_options : { base_filter : { active :"t" } },
1183                 onChange : function(val) {
1184                     pane.setFieldValue('shipper', val);
1185                     validateInvIdent(
1186                         invoicePane && invoicePane.getFieldValue("inv_ident"),
1187                         val,
1188                         invoicePane && invoicePane.getFieldValue("receiver")
1189                     );
1190                 }
1191             } 
1192         },
1193         shipper  : { dijitArgs : { store_options : { base_filter : { active :"t" } } } }
1194     });
1195
1196     for(var field in args) {
1197         override[field] = {widgetValue : args[field]};
1198     }
1199
1200     // push the name of the invoice into the name display field after update
1201     override.inv_ident = dojo.mixin(
1202         override.inv_ident,
1203         {dijitArgs : {onChange :
1204             function(newVal) {
1205                 validateInvIdent(
1206                     newVal,
1207                     invoicePane && invoicePane.getFieldValue("provider"),
1208                     invoicePane && invoicePane.getFieldValue("receiver")
1209                 );
1210
1211                 if (dojo.byId('acq-invoice-summary-name'))
1212                     dojo.byId('acq-invoice-summary-name').innerHTML = newVal;
1213             }
1214         }}
1215     );
1216
1217
1218     pane = new openils.widget.EditPane({
1219         fmObject : inv,
1220         paneStackCount : 2,
1221         fmClass : 'acqinv',
1222         mode : (inv) ? 'edit' : 'create',
1223         hideActionButtons : true,
1224         overrideWidgetArgs : override,
1225         readOnly : (inv) && openils.Util.isTrue(inv.complete()),
1226         requiredFields : [
1227             'inv_ident', 
1228             'recv_date', 
1229             'provider', 
1230             'shipper'
1231         ],
1232         fieldOrder : [
1233             'inv_ident', 
1234             'recv_date', 
1235             'recv_method', 
1236             'inv_type', 
1237             'provider', 
1238             'shipper'
1239         ],
1240         suppressFields : ['id', 'complete']
1241     });
1242
1243     pane.startup();
1244     parentNode.appendChild(pane.domNode);
1245     return pane;
1246 }
1247
1248
1249 function createExtraCopies(oncomplete) {
1250
1251     var lids = [];
1252     for(var liId in extraCopies) {
1253         var data = extraCopies[liId];
1254         for(var i = 0; i < data.numExtra; i++) {
1255             var lid = new fieldmapper.acqlid();
1256             lid.isnew(true);
1257             lid.lineitem(liId);
1258             lid.fund(data.fund);
1259             lid.recv_time('now');
1260             lids.push(lid);
1261         }
1262     }
1263
1264     if(lids.length == 0) 
1265         return oncomplete();
1266
1267     fieldmapper.standardRequest(
1268         ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1269         {
1270             params : [openils.User.authtoken, lids, true],
1271             oncomplete : function(r) {
1272                 if(openils.Util.readResponse(r))
1273                     oncomplete();
1274             }
1275         }
1276     );
1277
1278 }
1279
1280 function smartSearchSubmitter() {
1281     performSearch(0, !dojo.byId('acq-unified-build-progressively').checked);
1282 }
1283
1284
1285 openils.Util.addOnLoad(init);
1286
1287