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