]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/invoice/view.js
moved money summary boxes to regular in-markup dijits
[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
14 dojo.requireLocalization('openils.acq', 'acq');
15 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
16
17 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
18 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
19
20 var cgi = new openils.CGI();
21 var pcrud = new openils.PermaCrud();
22 var attachLi;
23 var attachPo;
24 var invoice;
25 var itemTbody;
26 var itemTemplate;
27 var entryTemplate;
28 var totalInvoicedBox;
29 var totalPaidBox;
30 var balanceOwedBox;
31 var invoicePane;
32 var itemTypes;
33 var virtualId = -1;
34 var widgetRegistry = {acqie : {}, acqii : {}};
35
36 function nodeByName(name, context) {
37     return dojo.query('[name='+name+']', context)[0];
38 }
39
40 function init() {
41
42     attachLi = cgi.param('attach_li');
43     attachPo = cgi.param('attach_po');
44
45     itemTypes = pcrud.retrieveAll('aiit');
46
47     if(cgi.param('create')) {
48         renderInvoice();
49
50     } else {
51         fieldmapper.standardRequest(
52             ['open-ils.acq', 'open-ils.acq.invoice.retrieve'],
53             {
54                 params : [openils.User.authtoken, invoiceId],
55                 oncomplete : function(r) {
56                     invoice = openils.Util.readResponse(r);     
57                     renderInvoice();
58                 }
59             }
60         );
61     }
62 }
63
64 function renderInvoice() {
65
66     // in create mode, let the LI or PO render the invoice with seed data
67     if( !(cgi.param('create') && (attachPo || attachLi)) ) {
68         invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), invoice);
69     }
70
71     dojo.byId('acq-invoice-new-item').onclick = function() {
72         var item = new fieldmapper.acqii();
73         item.id(virtualId--);
74         item.isnew(true);
75         addInvoiceItem(item);
76     }
77
78     updateTotalCost();
79
80     if(invoice) {
81         dojo.forEach(
82             invoice.items(),
83             function(item) {
84                 addInvoiceItem(item);
85             }
86         );
87
88         dojo.forEach(
89             invoice.entries(),
90             function(entry) {
91                 addInvoiceEntry(entry);
92             }
93         );
94     }
95
96     if(attachLi) doAttachLi();
97     if(attachPo) doAttachPo();
98 }
99
100 function doAttachLi() {
101
102     fieldmapper.standardRequest(
103         ["open-ils.acq", "open-ils.acq.lineitem.retrieve"], {
104             async: true,
105             params: [openils.User.authtoken, attachLi, {
106                 clear_marc : true,
107                 flesh_attrs : true,
108                 flesh_po : true,
109                 flesh_li_details : true,
110                 flesh_fund_debit : true
111             }],
112             oncomplete: function(r) { 
113                 lineitem = openils.Util.readResponse(r);
114
115                 if(cgi.param('create')) {
116                     // render the invoice using some seed data from the Lineitem
117                     var invoiceArgs = {provider : lineitem.provider(), shipper : lineitem.provider()}; 
118                     invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), null, invoiceArgs);
119                 }
120
121                 var entry = new fieldmapper.acqie();
122                 entry.id(virtualId--);
123                 entry.isnew(true);
124                 entry.lineitem(lineitem);
125                 entry.purchase_order(lineitem.purchase_order());
126                 addInvoiceEntry(entry);
127             }
128         }
129     );
130 }
131
132 function doAttachPo() {
133     fieldmapper.standardRequest(
134         ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
135         {   async: true,
136             params: [openils.User.authtoken, attachPo, {
137                 flesh_lineitems : true,
138                 clear_marc : true,
139                 flesh_lineitem_details : true,
140                 flesh_fund_debit : true
141             }],
142             oncomplete: function(r) {
143                 var po = openils.Util.readResponse(r);
144
145                 if(cgi.param('create')) {
146                     // render the invoice using some seed data from the PO
147                     var invoiceArgs = {provider : po.provider(), shipper : po.provider()}; 
148                     invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), null, invoiceArgs);
149                 }
150
151                 dojo.forEach(po.lineitems(), 
152                     function(lineitem) {
153                         var entry = new fieldmapper.acqie();
154                         entry.id(virtualId--);
155                         entry.isnew(true);
156                         entry.lineitem(lineitem);
157                         entry.purchase_order(po);
158                         lineitem.purchase_order(po);
159                         addInvoiceEntry(entry);
160                     }
161                 );
162             }
163         }
164     );
165 }
166
167 function updateTotalCost() {
168
169     var totalCost = 0;    
170     for(var id in widgetRegistry.acqii) 
171         if(!widgetRegistry.acqii[id]._object.isdeleted())
172             totalCost += widgetRegistry.acqii[id].cost_billed.getFormattedValue();
173     for(var id in widgetRegistry.acqie) 
174         if(!widgetRegistry.acqie[id]._object.isdeleted())
175             totalCost += widgetRegistry.acqie[id].cost_billed.getFormattedValue();
176     totalInvoicedBox.attr('value', totalCost);
177
178     totalPaid = 0;    
179     for(var id in widgetRegistry.acqii) 
180         if(!widgetRegistry.acqii[id]._object.isdeleted())
181             totalPaid += widgetRegistry.acqii[id].amount_paid.getFormattedValue();
182     for(var id in widgetRegistry.acqie) 
183         if(!widgetRegistry.acqie[id]._object.isdeleted())
184             totalPaid += widgetRegistry.acqie[id].amount_paid.getFormattedValue();
185     totalPaidBox.attr('value', totalPaid);
186
187     var buttonsDisabled = false;
188     if(totalPaid > totalCost || totalPaid < 0) {
189         openils.Util.addCSSClass(totalPaidBox.domNode, 'acq-invoice-invalid-amount');
190         invoiceSaveButton.attr('disabled', true);
191         invoiceProrateButton.attr('disabled', true);
192         buttonsDisabled = true;
193     } else {
194         openils.Util.removeCSSClass(totalPaidBox.domNode, 'acq-invoice-invalid-amount');
195         invoiceSaveButton.attr('disabled', false);
196         invoiceProrateButton.attr('disabled', false);
197     }
198
199     if(totalCost < 0) {
200         openils.Util.addCSSClass(totalInvoicedBox.domNode, 'acq-invoice-invalid-amount');
201         invoiceSaveButton.attr('disabled', true);
202         invoiceProrateButton.attr('disabled', true);
203     } else {
204         openils.Util.removeCSSClass(totalInvoicedBox.domNode, 'acq-invoice-invalid-amount');
205         if(!buttonsDisabled) {
206             invoiceSaveButton.attr('disabled', false);
207             invoiceProrateButton.attr('disabled', false);
208         }
209     }
210
211     balanceOwedBox.attr('value', (totalCost - totalPaid));
212 }
213
214
215 function registerWidget(obj, field, widget, callback) {
216     var blob = widgetRegistry[obj.classname];
217     if(!blob[obj.id()]) 
218         blob[obj.id()] = {_object : obj};
219     blob[obj.id()][field] = widget;
220     widget.build(
221         function(w, ww) {
222             dojo.connect(w, 'onChange', 
223                 function(newVal) { 
224                     obj.ischanged(true); 
225                     updateTotalCost();
226                 }
227             );
228             if(callback) callback(w, ww);
229         }
230     );
231     return widget;
232 }
233
234 function addInvoiceItem(item) {
235     itemTbody = dojo.byId('acq-invoice-item-tbody');
236     if(itemTemplate == null) {
237         itemTemplate = itemTbody.removeChild(dojo.byId('acq-invoice-item-template'));
238     }
239
240     var row = itemTemplate.cloneNode(true);
241     var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
242
243     dojo.forEach(
244         ['title', 'author', 'cost_billed', 'amount_paid'], 
245         function(field) {
246             registerWidget(
247                 item,
248                 field,
249                 new openils.widget.AutoFieldWidget({
250                     fmClass : 'acqii',
251                     fmObject : item,
252                     fmField : field,
253                     dijitArgs : (field == 'cost_billed' || field == 'amount_paid') ? {required : true, style : 'width: 6em'} : null,
254                     parentNode : nodeByName(field, row)
255                 })
256             )
257         }
258     );
259
260
261     /* ----------- fund -------------- */
262     var fundArgs = {
263         fmClass : 'acqii',
264         fmObject : item,
265         fmField : 'fund',
266         labelFormat : fundLabelFormat,
267         searchFormat : fundSearchFormat,
268         parentNode : nodeByName('fund', row)
269     }
270
271     if(item.fund_debit()) {
272         fundArgs.searchFilter = {'-or' : [{active : 't'}, {id : item.fund()}]};
273     } else {
274         fundArgs.searchFilter = {active : 't'}
275         if(itemType && openils.Util.isTrue(itemType.prorate()))
276             fundArgs.dijitArgs = {disabled : true};
277     }
278
279     var fundWidget = new openils.widget.AutoFieldWidget(fundArgs);
280     registerWidget(item, 'fund', fundWidget);
281
282     /* ---------- inv_item_type ------------- */
283
284     registerWidget(
285         item,
286         'inv_item_type',
287         new openils.widget.AutoFieldWidget({
288             fmObject : item,
289             fmField : 'inv_item_type',
290             parentNode : nodeByName('inv_item_type', row),
291             dijitArgs : {required : true}
292         }),
293         function(w, ww) {
294             // When the inv_item_type is set to prorate=true, don't allow the user the edit the fund
295             // since this charge will be prorated against (potentially) multiple funds
296             dojo.connect(w, 'onChange', 
297                 function() {
298                     if(!item.fund_debit()) {
299                         var itemType = itemTypes.filter(function(t) { return (t.code() == w.attr('value')) })[0];
300                         if(!itemType) return;
301                         if(openils.Util.isTrue(itemType.prorate())) {
302                             fundWidget.widget.attr('disabled', true);
303                             fundWidget.widget.attr('value', '');
304                         } else {
305                             fundWidget.widget.attr('disabled', false);
306                         }
307                     }
308                 }
309             );
310         }
311     );
312
313     nodeByName('delete', row).onclick = function() {
314         var cost = widgetRegistry.acqii[item.id()].cost_billed.getFormattedValue();
315         var msg = dojo.string.substitute(
316             localeStrings.INVOICE_CONFIRM_ITEM_DELETE, [
317                 cost,
318                 widgetRegistry.acqii[item.id()].inv_item_type.getFormattedValue()
319             ]
320         );
321         if(!confirm(msg)) return;
322         itemTbody.removeChild(row);
323         item.isdeleted(true);
324         if(item.isnew())
325             delete widgetRegistry.acqii[item.id()];
326         updateTotalCost();
327     }
328
329     itemTbody.appendChild(row);
330     updateTotalCost();
331 }
332
333 function addInvoiceEntry(entry) {
334     entryTbody = dojo.byId('acq-invoice-entry-tbody');
335     if(entryTemplate == null) {
336         entryTemplate = entryTbody.removeChild(dojo.byId('acq-invoice-entry-template'));
337     }
338
339     if(dojo.query('[lineitem=' + entry.lineitem().id() +']', entryTbody)[0])
340         // Is it ever valid to have multiple entries for 1 lineitem in a single invoice?
341         return;
342
343     var row = entryTemplate.cloneNode(true);
344     row.setAttribute('lineitem', entry.lineitem().id());
345     var lineitem = entry.lineitem();
346
347     var idents = [];
348     if(liMarcAttr(lineitem, 'isbn')) idents.push(liMarcAttr(lineitem, 'isbn'));
349     if(liMarcAttr(lineitem, 'upc')) idents.push(liMarcAttr(lineitem, 'upc'));
350     if(liMarcAttr(lineitem, 'issn')) idents.push(liMarcAttr(lineitem, 'issn'));
351
352     var lids = lineitem.lineitem_details();
353     var numOrdered = lids.length;
354     var numReceived = lids.filter(function(lid) { return (lid.recv_time() != null) }).length;
355     var numInvoiced = lids.filter(function(lid) { return !openils.Util.isTrue(lid.fund_debit().encumbrance()) }).length;
356
357     var poName = '';
358     var poId = '';
359     var po = entry.purchase_order();
360     if(po) {
361         poName = po.name();
362         poId = po.id();
363     }
364
365     nodeByName('title_details', row).innerHTML = 
366         dojo.string.substitute(
367             localeStrings.INVOICE_TITLE_DETAILS, [
368                 liMarcAttr(lineitem, 'title'),
369                 liMarcAttr(lineitem, 'author'),
370                 idents.join(','),
371                 numOrdered,
372                 numReceived,
373                 Number(lineitem.estimated_unit_price()).toFixed(2),
374                 (Number(lineitem.estimated_unit_price()) * numOrdered).toFixed(2),
375                 numInvoiced,
376                 lineitem.id(),
377                 oilsBasePath,
378                 poId,
379                 poName
380             ]
381         );
382
383
384     dojo.forEach(
385         ['inv_item_count', 'phys_item_count', 'cost_billed', 'amount_paid'],
386         function(field) {
387             var dijitArgs = {required : true, constraints : {min: 0}, style : 'width:6em'};
388             if(entry.isnew() && field == 'phys_item_count') dijitArgs.value = numReceived;
389             registerWidget(
390                 entry, 
391                 field,
392                 new openils.widget.AutoFieldWidget({
393                     fmObject : entry,
394                     fmClass : 'acqie',
395                     fmField : field,
396                     dijitArgs : dijitArgs,
397                     parentNode : nodeByName(field, row)
398                 })
399             );
400         }
401     );
402
403     nodeByName('detach', row).onclick = function() {
404         var cost = widgetRegistry.acqie[entry.id()].cost_billed.getFormattedValue();
405         var msg = dojo.string.substitute(
406             localeStrings.INVOICE_CONFIRM_ENTRY_DETACH, [
407                 cost || 0,
408                 liMarcAttr(lineitem, 'title'),
409                 liMarcAttr(lineitem, 'author'),
410                 idents.join(',')
411             ]
412         );
413         if(!confirm(msg)) return;
414         entryTbody.removeChild(row);
415         entry.isdeleted(true);
416         if(entry.isnew())
417             delete widgetRegistry.acqie[entry.id()];
418         updateTotalCost();
419     }
420
421     entryTbody.appendChild(row);
422     updateTotalCost();
423 }
424
425 function liMarcAttr(lineitem, name) {
426     var attr = lineitem.attributes().filter(
427         function(attr) { 
428             if(
429                 attr.attr_type() == 'lineitem_marc_attr_definition' && 
430                 attr.attr_name() == name) 
431                     return attr 
432         } 
433     )[0];
434     return (attr) ? attr.attr_value() : '';
435 }
436
437 function saveChanges(doProrate) {
438     
439     progressDialog.show(true);
440
441     var updateItems = [];
442     for(var id in widgetRegistry.acqii) {
443         var reg = widgetRegistry.acqii[id];
444         var item = reg._object;
445         if(item.ischanged() || item.isnew() || item.isdeleted()) {
446             updateItems.push(item);
447             if(item.isnew()) item.id(null);
448             for(var field in reg) {
449                 if(field != '_object')
450                     item[field]( reg[field].getFormattedValue() );
451             }
452             
453             // unflesh
454             if(item.purchase_order() != null && typeof item.purchase_order() == 'object')
455                 item.purchase_order( item.purchase_order().id() );
456         }
457     }
458
459     var updateEntries = [];
460     for(var id in widgetRegistry.acqie) {
461         var reg = widgetRegistry.acqie[id];
462         var entry = reg._object;
463         if(entry.ischanged() || entry.isnew() || entry.isdeleted()) {
464             entry.lineitem(entry.lineitem().id());
465             entry.purchase_order(entry.purchase_order().id());
466             updateEntries.push(entry);
467             if(entry.isnew()) entry.id(null);
468
469             for(var field in reg) {
470                 if(field != '_object')
471                     entry[field]( reg[field].getFormattedValue() );
472             }
473             
474             // unflesh
475             dojo.forEach(['purchase_order', 'lineitem'],
476                 function(field) {
477                     if(entry[field]() != null && typeof entry[field]() == 'object')
478                         entry[field]( entry[field]().id() );
479                 }
480             );
481         }
482     }
483
484     if(!invoice) {
485         invoice = new fieldmapper.acqinv();
486         invoice.isnew(true);
487     } else {
488         invoice.ischanged(true); // for now, just always update
489     }
490
491     dojo.forEach(invoicePane.fieldList, 
492         function(field) {
493             invoice[field.name]( field.widget.getFormattedValue() );
494         }
495     );
496
497     fieldmapper.standardRequest(
498         ['open-ils.acq', 'open-ils.acq.invoice.update'],
499         {
500             params : [openils.User.authtoken, invoice, updateEntries, updateItems],
501             oncomplete : function(r) {
502                 progressDialog.hide();
503                 var invoice = openils.Util.readResponse(r);
504                 if(invoice) {
505                     if(doProrate)
506                         return prorateInvoice(invoice);
507                     location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
508                 }
509             }
510         }
511     );
512 }
513
514 function prorateInvoice(invoice) {
515     if(!confirm(localeStrings.INVOICE_CONFIRM_PRORATE)) return;
516     progressDialog.show(true);
517
518     fieldmapper.standardRequest(
519         ['open-ils.acq', 'open-ils.acq.invoice.apply_prorate'],
520         {
521             params : [openils.User.authtoken, invoice.id()],
522             oncomplete : function(r) {
523                 progressDialog.hide();
524                 var invoice = openils.Util.readResponse(r);
525                 if(invoice) {
526                     location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
527                 }
528             }
529         }
530     );
531
532 }
533
534
535
536 openils.Util.addOnLoad(init);
537
538