]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/invoice/view.js
added pcrud entries for po_items, repaired pcrud entries for po notes
[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('dijit.form.CheckBox');
4 dojo.require('dijit.form.CurrencyTextBox');
5 dojo.require('dijit.form.NumberTextBox');
6 dojo.require('openils.User');
7 dojo.require('openils.Util');
8 dojo.require('openils.CGI');
9 dojo.require('openils.PermaCrud');
10 dojo.require('openils.widget.EditPane');
11 dojo.require('openils.widget.AutoFieldWidget');
12 dojo.require('openils.widget.ProgressDialog');
13 dojo.require('openils.acq.Lineitem');
14
15 dojo.requireLocalization('openils.acq', 'acq');
16 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
17
18 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
19 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
20
21 var cgi = new openils.CGI();
22 var pcrud = new openils.PermaCrud();
23 var attachLi;
24 var attachPo;
25 var invoice;
26 var itemTbody;
27 var itemTemplate;
28 var entryTemplate;
29 var totalInvoicedBox;
30 var totalPaidBox;
31 var balanceOwedBox;
32 var invoicePane;
33 var itemTypes;
34 var virtualId = -1;
35 var extraCopies = {};
36 var extraCopiesFund;
37 var widgetRegistry = {acqie : {}, acqii : {}};
38
39 function nodeByName(name, context) {
40     return dojo.query('[name='+name+']', context)[0];
41 }
42
43 function init() {
44
45     attachLi = cgi.param('attach_li');
46     attachPo = cgi.param('attach_po');
47
48     itemTypes = pcrud.retrieveAll('aiit');
49
50     if(cgi.param('create')) {
51         renderInvoice();
52
53     } else {
54         fieldmapper.standardRequest(
55             ['open-ils.acq', 'open-ils.acq.invoice.retrieve'],
56             {
57                 params : [openils.User.authtoken, invoiceId],
58                 oncomplete : function(r) {
59                     invoice = openils.Util.readResponse(r);     
60                     renderInvoice();
61                 }
62             }
63         );
64     }
65
66     extraCopiesFund = new openils.widget.AutoFieldWidget({
67         fmField : 'fund',
68         fmClass : 'acqlid',
69         searchFilter : {active : 't'},
70         labelFormat : fundLabelFormat,
71         searchFormat : fundSearchFormat,
72         dijitArgs : {required : true},
73         parentNode : dojo.byId('acq-invoice-extra-copies-fund')
74     });
75     extraCopiesFund.build();
76 }
77
78 function renderInvoice() {
79
80     // in create mode, let the LI or PO render the invoice with seed data
81     if( !(cgi.param('create') && (attachPo || attachLi)) ) {
82         invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), invoice);
83     }
84
85     dojo.byId('acq-invoice-new-item').onclick = function() {
86         var item = new fieldmapper.acqii();
87         item.id(virtualId--);
88         item.isnew(true);
89         addInvoiceItem(item);
90     }
91
92     updateTotalCost();
93
94     if(invoice && openils.Util.isTrue(invoice.complete())) {
95
96         dojo.forEach( // hide widgets that should not be visible for a completed invoice
97             dojo.query('.hide-complete'), 
98             function(node) { openils.Util.hide(node); }
99         );
100
101         new openils.User().getPermOrgList(
102             'ACQ_INVOICE_REOPEN', 
103             function (orgs) {
104                 if(orgs.indexOf(invoice.receiver()) >= 0)
105                     openils.Util.show('acq-invoice-reopen-button-wrapper', 'inline');
106             }, 
107             true, 
108             true
109         );
110     }
111
112     if(invoice) {
113         dojo.forEach(
114             invoice.items(),
115             function(item) {
116                 addInvoiceItem(item);
117             }
118         );
119
120         dojo.forEach(
121             invoice.entries(),
122             function(entry) {
123                 addInvoiceEntry(entry);
124             }
125         );
126     }
127
128     if(attachLi) doAttachLi();
129     if(attachPo) doAttachPo();
130 }
131
132 function doAttachLi() {
133
134     //var invoiceArgs = {provider : lineitem.provider(), shipper : lineitem.provider()}; 
135     if(cgi.param('create')) {
136         var invoiceArgs = {};
137         invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), null, invoiceArgs);
138     }
139     var entry = new fieldmapper.acqie();
140     entry.id(virtualId--);
141     entry.isnew(true);
142     entry.lineitem(attachLi);
143     addInvoiceEntry(entry);
144 }
145
146 function doAttachPo() {
147
148     fieldmapper.standardRequest(
149         ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
150         {   async: true,
151             params: [
152                 openils.User.authtoken, attachPo, 
153                 {flesh_lineitem_ids : true, flesh_po_items : true}
154             ],
155             oncomplete: function(r) {
156                 var po = openils.Util.readResponse(r);
157
158                 if(cgi.param('create')) {
159                     // render the invoice using some seed data from the PO
160                     var invoiceArgs = {provider : po.provider(), shipper : po.provider()}; 
161                     invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), null, invoiceArgs);
162                 }
163
164                 dojo.forEach(po.lineitems(), 
165                     function(lineitem) {
166                         var entry = new fieldmapper.acqie();
167                         entry.id(virtualId--);
168                         entry.isnew(true);
169                         entry.lineitem(lineitem);
170                         entry.purchase_order(po);
171                         addInvoiceEntry(entry);
172                     }
173                 );
174
175                 dojo.forEach(po.po_items(),
176                     function(poItem) {
177                         var item = new fieldmapper.acqii();
178                         item.id(virtualId--);
179                         item.isnew(true);
180                         item.fund(poItem.fund());
181                         item.title(poItem.title());
182                         item.author(poItem.author());
183                         item.note(poItem.note());
184                         item.inv_item_type(poItem.inv_item_type());
185                         item.purchase_order(po);
186                         item.po_item(poItem);
187                         addInvoiceItem(item);
188                     }
189                 );
190             }
191         }
192     );
193 }
194
195 function updateTotalCost() {
196
197     var totalCost = 0;    
198     for(var id in widgetRegistry.acqii) 
199         if(!widgetRegistry.acqii[id]._object.isdeleted())
200             totalCost += Number(widgetRegistry.acqii[id].cost_billed.getFormattedValue());
201     for(var id in widgetRegistry.acqie) 
202         if(!widgetRegistry.acqie[id]._object.isdeleted())
203             totalCost += Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue());
204     totalInvoicedBox.attr('value', totalCost);
205
206     totalPaid = 0;    
207     for(var id in widgetRegistry.acqii) 
208         if(!widgetRegistry.acqii[id]._object.isdeleted())
209             totalPaid += Number(widgetRegistry.acqii[id].amount_paid.getFormattedValue());
210     for(var id in widgetRegistry.acqie) 
211         if(!widgetRegistry.acqie[id]._object.isdeleted())
212             totalPaid += Number(widgetRegistry.acqie[id].amount_paid.getFormattedValue());
213     totalPaidBox.attr('value', totalPaid);
214
215     var buttonsDisabled = false;
216
217     if(totalPaid > totalCost || totalPaid < 0) {
218         openils.Util.addCSSClass(totalPaidBox.domNode, 'acq-invoice-invalid-amount');
219         invoiceSaveButton.attr('disabled', true);
220         invoiceProrateButton.attr('disabled', true);
221         buttonsDisabled = true;
222     } else {
223         openils.Util.removeCSSClass(totalPaidBox.domNode, 'acq-invoice-invalid-amount');
224         invoiceSaveButton.attr('disabled', false);
225         invoiceProrateButton.attr('disabled', false);
226     }
227
228     if(totalCost < 0) {
229         openils.Util.addCSSClass(totalInvoicedBox.domNode, 'acq-invoice-invalid-amount');
230         invoiceSaveButton.attr('disabled', true);
231         invoiceProrateButton.attr('disabled', true);
232     } else {
233         openils.Util.removeCSSClass(totalInvoicedBox.domNode, 'acq-invoice-invalid-amount');
234         if(!buttonsDisabled) {
235             invoiceSaveButton.attr('disabled', false);
236             invoiceProrateButton.attr('disabled', false);
237         }
238     }
239
240     if(totalPaid == totalCost) { // XXX: too rigid?
241         invoiceCloseButton.attr('disabled', false);
242     } else {
243         invoiceCloseButton.attr('disabled', true);
244     }
245
246     balanceOwedBox.attr('value', (totalCost - totalPaid));
247 }
248
249
250 function registerWidget(obj, field, widget, callback) {
251     var blob = widgetRegistry[obj.classname];
252     if(!blob[obj.id()]) 
253         blob[obj.id()] = {_object : obj};
254     blob[obj.id()][field] = widget;
255     widget.build(
256         function(w, ww) {
257             dojo.connect(w, 'onChange', 
258                 function(newVal) { 
259                     obj.ischanged(true); 
260                     updateTotalCost();
261                 }
262             );
263             if(callback) callback(w, ww);
264         }
265     );
266     return widget;
267 }
268
269 function addInvoiceItem(item) {
270     itemTbody = dojo.byId('acq-invoice-item-tbody');
271     if(itemTemplate == null) {
272         itemTemplate = itemTbody.removeChild(dojo.byId('acq-invoice-item-template'));
273     }
274
275     var row = itemTemplate.cloneNode(true);
276     var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
277
278     dojo.forEach(
279         ['title', 'author', 'cost_billed', 'amount_paid'], 
280         function(field) {
281             
282             var args;
283             if(field == 'title' || field == 'author') {
284                 //args = {style : 'width:10em'};
285             } else if(field == 'cost_billed' || field == 'amount_paid') {
286                 args = {required : true, style : 'width: 6em'};
287             }
288             registerWidget(
289                 item,
290                 field,
291                 new openils.widget.AutoFieldWidget({
292                     fmClass : 'acqii',
293                     fmObject : item,
294                     fmField : field,
295                     readOnly : invoice && openils.Util.isTrue(invoice.complete()),
296                     dijitArgs : args,
297                     parentNode : nodeByName(field, row)
298                 })
299             )
300         }
301     );
302
303
304     /* ----------- fund -------------- */
305     var fundArgs = {
306         fmClass : 'acqii',
307         fmObject : item,
308         fmField : 'fund',
309         labelFormat : fundLabelFormat,
310         searchFormat : fundSearchFormat,
311         readOnly : invoice && openils.Util.isTrue(invoice.complete()),
312         dijitArgs : {required : true},
313         parentNode : nodeByName('fund', row)
314     }
315
316     if(item.fund_debit()) {
317         fundArgs.searchFilter = {'-or' : [{active : 't'}, {id : item.fund()}]};
318     } else {
319         fundArgs.searchFilter = {active : 't'}
320         if(itemType && openils.Util.isTrue(itemType.prorate()))
321             fundArgs.dijitArgs = {disabled : true};
322     }
323
324     var fundWidget = new openils.widget.AutoFieldWidget(fundArgs);
325     registerWidget(item, 'fund', fundWidget);
326
327     /* ---------- inv_item_type ------------- */
328
329     if(item.po_item()) {
330
331         // read-only item view for items that were the result of a po-item
332         var po = item.purchase_order();
333         var po_item = item.po_item();
334         var node = nodeByName('inv_item_type', row);
335         var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
336
337         node.innerHTML = dojo.string.substitute(
338             localeStrings.INVOICE_ITEM_PO_DETAILS, 
339             [ 
340                 itemType.name(),
341                 oilsBasePath, 
342                 po.id(), 
343                 po.name(), 
344                 dojo.date.locale.format(dojo.date.stamp.fromISOString(po.order_date()), {selector:'date'}),
345                 po_item.estimated_cost() 
346             ]
347         );
348
349     } else {
350
351         registerWidget(
352             item,
353             'inv_item_type',
354             new openils.widget.AutoFieldWidget({
355                 fmObject : item,
356                 fmField : 'inv_item_type',
357                 parentNode : nodeByName('inv_item_type', row),
358                 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
359                 dijitArgs : {required : true}
360             }),
361             function(w, ww) {
362                 // When the inv_item_type is set to prorate=true, don't allow the user the edit the fund
363                 // since this charge will be prorated against (potentially) multiple funds
364                 dojo.connect(w, 'onChange', 
365                     function() {
366                         if(!item.fund_debit()) {
367                             var itemType = itemTypes.filter(function(t) { return (t.code() == w.attr('value')) })[0];
368                             if(!itemType) return;
369                             if(openils.Util.isTrue(itemType.prorate())) {
370                                 fundWidget.widget.attr('disabled', true);
371                                 fundWidget.widget.attr('value', '');
372                             } else {
373                                 fundWidget.widget.attr('disabled', false);
374                             }
375                         }
376                     }
377                 );
378             }
379         );
380     }
381
382     nodeByName('delete', row).onclick = function() {
383         var cost = widgetRegistry.acqii[item.id()].cost_billed.getFormattedValue();
384         var msg = dojo.string.substitute(
385             localeStrings.INVOICE_CONFIRM_ITEM_DELETE, [
386                 cost,
387                 widgetRegistry.acqii[item.id()].inv_item_type.getFormattedValue()
388             ]
389         );
390         if(!confirm(msg)) return;
391         itemTbody.removeChild(row);
392         item.isdeleted(true);
393         if(item.isnew())
394             delete widgetRegistry.acqii[item.id()];
395         updateTotalCost();
396     }
397
398     itemTbody.appendChild(row);
399     updateTotalCost();
400 }
401
402 function addInvoiceEntry(entry) {
403
404     openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-header'), 'hidden');
405     openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-thead'), 'hidden');
406     openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-tbody'), 'hidden');
407
408     entryTbody = dojo.byId('acq-invoice-entry-tbody');
409     if(entryTemplate == null) {
410         entryTemplate = entryTbody.removeChild(dojo.byId('acq-invoice-entry-template'));
411     }
412
413     if(dojo.query('[lineitem=' + entry.lineitem() +']', entryTbody)[0])
414         // Is it ever valid to have multiple entries for 1 lineitem in a single invoice?
415         return;
416
417     var row = entryTemplate.cloneNode(true);
418     row.setAttribute('lineitem', entry.lineitem());
419
420     openils.acq.Lineitem.fetchAndRender(
421         entry.lineitem(), {}, 
422         function(li, html) { 
423             entry.lineitem(li);
424             entry.purchase_order(li.purchase_order());
425             nodeByName('title_details', row).innerHTML = html;
426
427             dojo.forEach(
428                 ['inv_item_count', 'phys_item_count', 'cost_billed', 'amount_paid'],
429                 function(field) {
430                     var dijitArgs = {required : true, constraints : {min: 0}, style : 'width:6em'};
431                     if(entry.isnew() && field == 'phys_item_count') {
432                         // by default, attempt to pay for all non-canceled and as-of-yet-un-invoiced items
433                         var count = Number(li.order_summary().item_count() || 0) - 
434                                     Number(li.order_summary().cancel_count() || 0) -
435                                     Number(li.order_summary().invoice_count() || 0);
436                         if(count < 0) count = 0;
437                         dijitArgs.value = count;
438                     }
439                     registerWidget(
440                         entry, 
441                         field,
442                         new openils.widget.AutoFieldWidget({
443                             fmObject : entry,
444                             fmClass : 'acqie',
445                             fmField : field,
446                             dijitArgs : dijitArgs,
447                             readOnly : invoice && openils.Util.isTrue(invoice.complete()),
448                             parentNode : nodeByName(field, row)
449                         }),
450                         function(w) {    
451                             if(field == 'phys_item_count') {
452                                 dojo.connect(w, 'onChange', 
453                                     function() {
454                                         // staff entered a higher number in the receive field than was originally ordered
455                                         // taking into account already invoiced items
456                                         var extra = Number(this.attr('value')) - 
457                                             (Number(entry.lineitem().item_count()) - Number(entry.lineitem().order_summary().invoice_count()));
458                                         if(extra > 0) {
459                                             storeExtraCopies(entry, extra);
460                                         }
461                                     }
462                                 )
463                             }
464                         }
465                     );
466                 }
467             );
468         }
469     );
470
471     nodeByName('detach', row).onclick = function() {
472         var cost = widgetRegistry.acqie[entry.id()].cost_billed.getFormattedValue();
473         var msg = dojo.string.substitute(
474             localeStrings.INVOICE_CONFIRM_ENTRY_DETACH, [
475                 cost || 0,
476                 liMarcAttr(lineitem, 'title'),
477                 liMarcAttr(lineitem, 'author'),
478                 idents.join(',')
479             ]
480         );
481         if(!confirm(msg)) return;
482         entryTbody.removeChild(row);
483         entry.isdeleted(true);
484         if(entry.isnew())
485             delete widgetRegistry.acqie[entry.id()];
486         updateTotalCost();
487     }
488
489     entryTbody.appendChild(row);
490     updateTotalCost();
491 }
492
493 function liMarcAttr(lineitem, name) {
494     var attr = lineitem.attributes().filter(
495         function(attr) { 
496             if(
497                 attr.attr_type() == 'lineitem_marc_attr_definition' && 
498                 attr.attr_name() == name) 
499                     return attr 
500         } 
501     )[0];
502     return (attr) ? attr.attr_value() : '';
503 }
504
505 function saveChanges(doProrate, doClose, doReopen) {
506     createExtraCopies(
507         function() {
508             saveChangesPartTwo(doProrate, doClose, doReopen);
509         }
510     );
511 }
512
513 function saveChangesPartTwo(doProrate, doClose, doReopen) {
514     
515     progressDialog.show(true);
516
517     if(doReopen) {
518         invoice.complete('f');
519
520     } else {
521
522
523         var updateItems = [];
524         for(var id in widgetRegistry.acqii) {
525             var reg = widgetRegistry.acqii[id];
526             var item = reg._object;
527             if(item.ischanged() || item.isnew() || item.isdeleted()) {
528                 updateItems.push(item);
529                 if(item.isnew()) item.id(null);
530                 for(var field in reg) {
531                     if(field != '_object')
532                         item[field]( reg[field].getFormattedValue() );
533                 }
534                 
535                 // unflesh
536                 if(item.purchase_order() != null && typeof item.purchase_order() == 'object')
537                     item.purchase_order( item.purchase_order().id() );
538             }
539         }
540
541         var updateEntries = [];
542         for(var id in widgetRegistry.acqie) {
543             var reg = widgetRegistry.acqie[id];
544             var entry = reg._object;
545             if(entry.ischanged() || entry.isnew() || entry.isdeleted()) {
546                 entry.lineitem(entry.lineitem().id());
547                 entry.purchase_order(entry.purchase_order().id());
548                 updateEntries.push(entry);
549                 if(entry.isnew()) entry.id(null);
550
551                 for(var field in reg) {
552                     if(field != '_object')
553                         entry[field]( reg[field].getFormattedValue() );
554                 }
555                 
556                 // unflesh
557                 dojo.forEach(['purchase_order', 'lineitem'],
558                     function(field) {
559                         if(entry[field]() != null && typeof entry[field]() == 'object')
560                             entry[field]( entry[field]().id() );
561                     }
562                 );
563             }
564         }
565
566         if(!invoice) {
567             invoice = new fieldmapper.acqinv();
568             invoice.isnew(true);
569         } else {
570             invoice.ischanged(true); // for now, just always update
571         }
572
573         dojo.forEach(invoicePane.fieldList, 
574             function(field) {
575                 invoice[field.name]( field.widget.getFormattedValue() );
576             }
577         );
578
579         if(doClose) 
580             invoice.complete('t');
581     }
582
583     fieldmapper.standardRequest(
584         ['open-ils.acq', 'open-ils.acq.invoice.update'],
585         {
586             params : [openils.User.authtoken, invoice, updateEntries, updateItems],
587             oncomplete : function(r) {
588                 progressDialog.hide();
589                 var invoice = openils.Util.readResponse(r);
590                 if(invoice) {
591                     if(doProrate)
592                         return prorateInvoice(invoice);
593                     location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
594                 }
595             }
596         }
597     );
598 }
599
600 function prorateInvoice(invoice) {
601     if(!confirm(localeStrings.INVOICE_CONFIRM_PRORATE)) return;
602     progressDialog.show(true);
603
604     fieldmapper.standardRequest(
605         ['open-ils.acq', 'open-ils.acq.invoice.apply_prorate'],
606         {
607             params : [openils.User.authtoken, invoice.id()],
608             oncomplete : function(r) {
609                 progressDialog.hide();
610                 var invoice = openils.Util.readResponse(r);
611                 if(invoice) {
612                     location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
613                 }
614             }
615         }
616     );
617 }
618
619 function storeExtraCopies(entry, numExtra) {
620
621     dojo.byId('acq-invoice-extra-copies-message').innerHTML = 
622         dojo.string.substitute(
623             localeStrings.INVOICE_EXTRA_COPIES, [numExtra]);
624
625     var addCopyHandler;
626     addCopyHandler = dojo.connect(
627         extraCopiesGo, 
628         'onClick',
629         function() {
630             extraCopies[entry.lineitem().id()] = {
631                 numExtra : numExtra, 
632                 fund : extraCopiesFund.widget.attr('value')
633             }
634             extraItemsDialog.hide();
635             dojo.disconnect(addCopyHandler);
636         }
637     );
638
639     dojo.connect(
640         extraCopiesCancel, 
641         'onClick',
642         function() { 
643             widgetRegistry.acqie[entry.id()].phys_item_count.widget.attr('value', '');
644             extraItemsDialog.hide() 
645         }
646     );
647
648     extraItemsDialog.show();
649 }
650
651 function createExtraCopies(oncomplete) {
652
653     var lids = [];
654     for(var liId in extraCopies) {
655         var data = extraCopies[liId];
656         for(var i = 0; i < data.numExtra; i++) {
657             var lid = new fieldmapper.acqlid();
658             lid.isnew(true);
659             lid.lineitem(liId);
660             lid.fund(data.fund);
661             lid.recv_time('now');
662             lids.push(lid);
663         }
664     }
665
666     if(lids.length == 0) 
667         return oncomplete();
668
669     fieldmapper.standardRequest(
670         ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
671         {
672             params : [openils.User.authtoken, lids, true],
673             oncomplete : function(r) {
674                 if(openils.Util.readResponse(r))
675                     oncomplete();
676             }
677         }
678     );
679
680 }
681
682
683 openils.Util.addOnLoad(init);
684
685