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');
17 dojo.requireLocalization('openils.acq', 'acq');
18 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
20 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
21 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
23 var cgi = new openils.CGI();
24 var pcrud = new openils.PermaCrud();
39 var widgetRegistry = {acqie : {}, acqii : {}};
41 var searchInitDone = false;
45 function nodeByName(name, context) {
46 return dojo.query('[name='+name+']', context)[0];
51 attachLi = cgi.param('attach_li') || [];
52 if (!dojo.isArray(attachLi))
53 attachLi = [attachLi];
55 attachPo = cgi.param('attach_po') || [];
56 if (!dojo.isArray(attachPo))
57 attachPo = [attachPo];
59 focusLineitem = new openils.CGI().param('focus_li');
61 totalInvoicedBox = dojo.byId('acq-total-invoiced-box');
62 totalPaidBox = dojo.byId('acq-total-paid-box');
63 balanceOwedBox = dojo.byId('acq-total-balance-box');
65 itemTypes = pcrud.retrieveAll('aiit');
67 dojo.byId('acq-invoice-summary-toggle-off').onclick = function() {
68 openils.Util.hide(dojo.byId('acq-invoice-summary'));
69 openils.Util.show(dojo.byId('acq-invoice-summary-small'));
72 dojo.byId('acq-invoice-summary-toggle-on').onclick = function() {
73 openils.Util.show(dojo.byId('acq-invoice-summary'));
74 openils.Util.hide(dojo.byId('acq-invoice-summary-small'));
77 if(cgi.param('create')) {
80 // show summary info by default for new invoices
81 dojo.byId('acq-invoice-summary-toggle-on').onclick();
84 dojo.byId('acq-invoice-summary-toggle-off').onclick();
85 fieldmapper.standardRequest(
86 ['open-ils.acq', 'open-ils.acq.invoice.retrieve.authoritative'],
88 params : [openils.User.authtoken, invoiceId],
89 oncomplete : function(r) {
90 invoice = openils.Util.readResponse(r);
97 extraCopiesFund = new openils.widget.AutoFieldWidget({
100 searchFilter : {active : 't'},
101 labelFormat : fundLabelFormat,
102 searchFormat : fundSearchFormat,
103 dijitArgs : {required : true},
104 parentNode : dojo.byId('acq-invoice-extra-copies-fund')
106 extraCopiesFund.build();
109 function renderInvoice() {
111 // in create mode, let the LI or PO render the invoice with seed data
112 if( !(cgi.param('create') && (attachPo.length || attachLi.length)) ) {
113 invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), invoice);
116 dojo.byId('acq-invoice-new-item').onclick = function() {
117 var item = new fieldmapper.acqii();
118 item.id(virtualId--);
120 addInvoiceItem(item);
125 if(invoice && openils.Util.isTrue(invoice.complete())) {
127 dojo.forEach( // hide widgets that should not be visible for a completed invoice
128 dojo.query('.hide-complete'),
129 function(node) { openils.Util.hide(node); }
132 new openils.User().getPermOrgList(
133 'ACQ_INVOICE_REOPEN',
135 if(orgs.indexOf(invoice.receiver()) >= 0)
136 openils.Util.show('acq-invoice-reopen-button-wrapper', 'inline');
143 // display items and entries in ID order
144 // which effectively equates to add order.
145 function idsort(a, b) { return a.id() < b.id() ? -1 : 1 }
149 invoice.items().sort(idsort),
151 addInvoiceItem(item);
156 invoice.entries().sort(idsort),
158 addInvoiceEntry(entry);
163 if(attachLi.length) doAttachLi();
164 if(attachPo.length) doAttachPo(0);
167 function doAttachLi(skipInit) {
169 //var invoiceArgs = {provider : lineitem.provider(), shipper : lineitem.provider()};
170 if(cgi.param('create') && !skipInit) {
172 // use the first LI in the list to determine the default provider
173 fieldmapper.standardRequest(
174 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
176 params : [openils.User.authtoken, attachLi[0], {clear_marc:1}],
177 oncomplete : function(r) {
178 var li = openils.Util.readResponse(r);
179 invoicePane = drawInvoicePane(
180 dojo.byId('acq-view-invoice-div'), null,
181 {provider : li.provider(), shipper : li.provider()}
188 dojo.forEach(attachLi,
190 var entry = new fieldmapper.acqie();
191 entry.id(virtualId--);
194 addInvoiceEntry(entry);
199 function doAttachPo(idx) {
201 if (idx == attachPo.length) return;
202 var poId = attachPo[idx];
204 fieldmapper.standardRequest(
205 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
208 openils.User.authtoken, poId,
209 {flesh_lineitem_ids : true, flesh_po_items : true}
211 oncomplete: function(r) {
212 var po = openils.Util.readResponse(r);
214 if(cgi.param('create') && idx == 0) {
215 // render the invoice using some seed data from the first PO
216 var invoiceArgs = {provider : po.provider(), shipper : po.provider()};
217 invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), null, invoiceArgs);
220 dojo.forEach(po.lineitems(),
222 var entry = new fieldmapper.acqie();
223 entry.id(virtualId--);
225 entry.lineitem(lineitem);
226 entry.purchase_order(po);
227 addInvoiceEntry(entry);
231 dojo.forEach(po.po_items(),
233 var item = new fieldmapper.acqii();
234 item.id(virtualId--);
236 item.fund(poItem.fund());
237 item.title(poItem.title());
238 item.author(poItem.author());
239 item.note(poItem.note());
240 item.inv_item_type(poItem.inv_item_type());
241 item.purchase_order(po);
242 item.po_item(poItem);
243 addInvoiceItem(item);
253 function performSearch(pageDir) {
254 clearSearchResTable();
255 var searchObject = termManager.buildSearchObject();
256 dojo.cookie('invs', base64Encode(searchObject));
257 dojo.cookie('invc', dojo.byId("acq-unified-conjunction").getValue());
259 if (pageDir == 0) { // new search
260 resultsLoader.displayOffset = 0;
262 resultsLoader.displayOffset += pageDir * resultsLoader.displayLimit;
265 if (resultsLoader.displayOffset == 0) {
266 openils.Util.hide('acq-inv-search-prev');
268 openils.Util.show('acq-inv-search-prev', 'inline');
271 if (dojo.byId('acq-invoice-search-limit-invoiceable').checked) {
272 if (!searchObject.jub)
273 searchObject.jub = [];
275 // exclude lineitems that are "cancelled" (sidebar: 'Mericans spell it 'canceled')
276 searchObject.jub.push({state : 'cancelled', '__not' : true});
278 // exclude lineitems already linked to this invoice
279 if (invoice && invoice.id() > 0) {
280 if (!searchObject.acqinv)
281 searchObject.acqinv = [];
282 searchObject.acqinv.push({id : invoice.id(), '__not' : true});
285 // limit to lineitems that have invoiceable copies
286 searchObject.acqlisumi = [{item_count : 1, '_gte' : true}];
288 // limit to provider if a provider is selected
289 var provider = invoicePane.getFieldValue('provider');
291 if (!searchObject.jub.filter(function(i) { return i.provider != null }).length)
292 searchObject.jub.push({provider : provider});
296 if (dojo.byId('acq-invoice-search-sort-title').checked) {
297 uriManager.order_by =
298 [ {"class": "acqlia", "field":"attr_value", "transform":"first"} ];
301 resultsLoader.lastSearch = searchObject;
302 resultManager.go(searchObject)
303 console.log('Lineitem Search: ' + js2JSON(searchObject));
304 focusLastSearchInput();
308 function renderUnifiedSearch() {
310 if (!searchInitDone) {
312 searchInitDone = true;
313 termManager = new TermManager();
314 resultManager = new ResultManager();
315 resultsLoader = new searchResultsLoader();
316 uriManager = new URIManager();
318 // define custom lineitem result handler
319 resultManager.result_types = {
321 "search_options": { "id_list": true },
322 "revealer": function() { },
323 "finisher": function() {
324 resultsLoader.batch_length = resultManager.count_results;
326 "adder": function(li) {
327 resultsLoader.addLineitem(li);
329 "interface": resultsLoader
332 "revealer": function() { }
336 var searchObject = dojo.cookie('invs');
337 console.log('loaded ' + searchObject);
339 // if there is a search object cookie, populate the search form
340 termManager.reflect(base64Decode(searchObject));
341 dojo.byId("acq-unified-conjunction").setValue(dojo.cookie('invc'));
343 console.log('adding row');
344 termManager.addRow();
348 dojo.addClass(dojo.byId('oils-acq-invoice-table'), 'hidden');
349 dojo.removeClass(dojo.byId('oils-acq-invoice-search'), 'hidden');
350 focusLastSearchInput();
353 function focusLastSearchInput() {
354 // TODO: see about making this better and moving it into search/unified.js
355 var wnodes = dojo.query('[name=widget]');
356 var inputNode = wnodes.item(wnodes.length - 1).firstChild;
366 var resultsTbody, resultsRow;
367 function searchResultsLoader() {
368 this.displayOffset = 0;
369 this.displayLimit = 10;
372 resultsTbody = dojo.byId('acq-invoice-search-results-tbody');
373 resultsRow = resultsTbody.removeChild(dojo.byId('acq-invoice-search-results-tr'));
376 this.addLineitem = function(li_id) {
377 console.log('Adding search result lineitem ' + li_id);
378 var row = resultsRow.cloneNode(true);
379 resultsTbody.appendChild(row);
380 var checkbox = dojo.query('[name=search-results-checkbox]', row)[0];
381 checkbox.setAttribute('lineitem', li_id);
383 // this lineitem is already part of the invoice
384 if (dojo.query('[entry_lineitem_row=' + li_id + ']')[0]) {
385 checkbox.disabled = true;
386 dojo.addClass(checkbox.parentNode, 'search-results-already-invoiced');
389 openils.acq.Lineitem.fetchAndRender(
392 dojo.query('[name=search-results-content-div]', row)[0].innerHTML = html;
398 function addSelectedToInvoice() {
399 var inputs = dojo.query('[name=search-results-checkbox]');
403 if (checkbox.checked) {
404 attachLi.push(checkbox.getAttribute('lineitem'));
405 checkbox.disabled = true;
406 checkbox.checked = false;
407 dojo.addClass(checkbox.parentNode, 'search-results-already-invoiced');
414 function clearSearchResTable() {
415 while (resultsTbody.childNodes[0])
416 resultsTbody.removeChild(resultsTbody.childNodes[0]);
419 function updateTotalCost() {
422 for(var id in widgetRegistry.acqii)
423 if(!widgetRegistry.acqii[id]._object.isdeleted())
424 totalCost += Number(widgetRegistry.acqii[id].cost_billed.getFormattedValue());
425 for(var id in widgetRegistry.acqie)
426 if(!widgetRegistry.acqie[id]._object.isdeleted())
427 totalCost += Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue());
428 totalInvoicedBox.innerHTML = totalCost.toFixed(2);
431 for(var id in widgetRegistry.acqii)
432 if(!widgetRegistry.acqii[id]._object.isdeleted())
433 totalPaid += Number(widgetRegistry.acqii[id].amount_paid.getFormattedValue());
434 for(var id in widgetRegistry.acqie)
435 if(!widgetRegistry.acqie[id]._object.isdeleted())
436 totalPaid += Number(widgetRegistry.acqie[id].amount_paid.getFormattedValue());
437 totalPaidBox.innerHTML = totalPaid.toFixed(2);
439 var buttonsDisabled = false;
441 if(totalPaid > totalCost || totalPaid < 0) {
442 openils.Util.addCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
443 invoiceSaveButton.attr('disabled', true);
444 invoiceProrateButton.attr('disabled', true);
445 buttonsDisabled = true;
447 openils.Util.removeCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
448 invoiceSaveButton.attr('disabled', false);
449 invoiceProrateButton.attr('disabled', false);
453 openils.Util.addCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
454 invoiceSaveButton.attr('disabled', true);
455 invoiceProrateButton.attr('disabled', true);
457 openils.Util.removeCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
458 if(!buttonsDisabled) {
459 invoiceSaveButton.attr('disabled', false);
460 invoiceProrateButton.attr('disabled', false);
464 if(totalPaid == totalCost) { // XXX: too rigid?
465 invoiceCloseButton.attr('disabled', false);
467 invoiceCloseButton.attr('disabled', true);
470 balanceOwedBox.innerHTML = (totalCost - totalPaid).toFixed(2);
472 updateExpectedCost();
476 function registerWidget(obj, field, widget, callback) {
477 var blob = widgetRegistry[obj.classname];
479 blob[obj.id()] = {_object : obj};
480 blob[obj.id()][field] = widget;
483 dojo.connect(w, 'onChange',
489 if(callback) callback(w, ww);
495 function addInvoiceItem(item) {
496 itemTbody = dojo.byId('acq-invoice-item-tbody');
497 if(itemTemplate == null) {
498 itemTemplate = itemTbody.removeChild(dojo.byId('acq-invoice-item-template'));
501 var row = itemTemplate.cloneNode(true);
502 var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
505 ['title', 'author', 'cost_billed', 'amount_paid'],
509 if(field == 'title' || field == 'author') {
510 //args = {style : 'width:10em'};
511 } else if(field == 'cost_billed' || field == 'amount_paid') {
512 args = {required : true, style : 'width: 8em'};
518 new openils.widget.AutoFieldWidget({
522 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
524 parentNode : nodeByName(field, row)
531 /* ----------- fund -------------- */
536 labelFormat : fundLabelFormat,
537 searchFormat : fundSearchFormat,
538 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
539 dijitArgs : {required : true},
540 parentNode : nodeByName('fund', row)
543 if(item.fund_debit()) {
544 fundArgs.searchFilter = {'-or' : [{active : 't'}, {id : item.fund()}]};
546 fundArgs.searchFilter = {active : 't'}
547 if(itemType && openils.Util.isTrue(itemType.prorate()))
548 fundArgs.dijitArgs = {disabled : true};
551 var fundWidget = new openils.widget.AutoFieldWidget(fundArgs);
552 registerWidget(item, 'fund', fundWidget);
554 /* ---------- inv_item_type ------------- */
558 // read-only item view for items that were the result of a po-item
559 var po = item.purchase_order();
560 var po_item = item.po_item();
561 var node = nodeByName('inv_item_type', row);
562 var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
563 orderDate = (!po.order_date()) ? '' :
564 dojo.date.locale.format(dojo.date.stamp.fromISOString(po.order_date()), {selector:'date'});
566 node.innerHTML = dojo.string.substitute(
567 localeStrings.INVOICE_ITEM_PO_DETAILS,
574 po_item.estimated_cost()
583 new openils.widget.AutoFieldWidget({
585 fmField : 'inv_item_type',
586 parentNode : nodeByName('inv_item_type', row),
587 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
588 dijitArgs : {required : true}
591 // When the inv_item_type is set to prorate=true, don't allow the user the edit the fund
592 // since this charge will be prorated against (potentially) multiple funds
593 dojo.connect(w, 'onChange',
595 if(!item.fund_debit()) {
596 var itemType = itemTypes.filter(function(t) { return (t.code() == w.attr('value')) })[0];
597 if(!itemType) return;
598 if(openils.Util.isTrue(itemType.prorate())) {
599 fundWidget.widget.attr('disabled', true);
600 fundWidget.widget.attr('value', '');
602 fundWidget.widget.attr('disabled', false);
611 nodeByName('delete', row).onclick = function() {
612 var cost = widgetRegistry.acqii[item.id()].cost_billed.getFormattedValue();
613 var msg = dojo.string.substitute(
614 localeStrings.INVOICE_CONFIRM_ITEM_DELETE, [
616 widgetRegistry.acqii[item.id()].inv_item_type.getFormattedValue() || ''
619 if(!confirm(msg)) return;
620 itemTbody.removeChild(row);
621 item.isdeleted(true);
623 delete widgetRegistry.acqii[item.id()];
627 itemTbody.appendChild(row);
631 function updateReceiveLink(li) {
633 return; /* can't do this with unsaved invoices */
635 var link = dojo.byId("acq-view-invoice-receive-link");
636 if (link.onclick) return; /* only need to do this once */
638 /* don't do this if there's nothing receivable on the lineitem */
639 if (li.order_summary().recv_count() + li.order_summary().cancel_count() >=
640 li.order_summary().item_count())
643 openils.Util.show("acq-view-invoice-receive");
644 link.onclick = function() { location.href = oilsBasePath + '/acq/invoice/receive/' + invoiceId; };
648 * Ensures focusLineitem is in view and causes a brief
649 * border around the lineitem to come to life then fade.
652 if (!focusLineitem) return;
654 // set during addLineitem()
655 var node = dojo.byId('li-title-ref-' + focusLineitem);
657 console.log('focus: li-title-ref-' + focusLineitem + ' : ' + node);
659 // LI may not yet be rendered
662 console.log('focusing ' + focusLineitem);
664 // prevent numerous re-focuses
665 focusLineitem = null;
667 // causes the full row to be visible
668 dijit.scrollIntoView(node);
670 dojo.require('dojox.fx');
674 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
680 // expected cost is totalCostInvoiced + totalCostNotYetInvoiced
681 function updateExpectedCost() {
683 var cost = Number(totalInvoicedBox.innerHTML || 0);
685 // for any LI's that are not yet billed (i.e. filled in)
686 // use the total expected cost for that lineitem.
687 for(var id in widgetRegistry.acqie) {
688 var entry = widgetRegistry.acqie[id]._object;
689 if(!entry.isdeleted()) {
690 if (Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue()) == 0) {
691 var li = entry.lineitem();
693 Number(li.order_summary().estimated_amount()) -
694 Number(li.order_summary().paid_amount());
699 dojo.byId('acq-invoice-summary-cost').innerHTML = cost.toFixed(2);
702 var invoicEntryWidgets = {};
703 function addInvoiceEntry(entry) {
704 console.log('Adding new entry for lineitem ' + entry.lineitem());
706 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-header'), 'hidden');
707 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-thead'), 'hidden');
708 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-tbody'), 'hidden');
710 dojo.byId('acq-invoice-summary-count').innerHTML =
711 Number(dojo.byId('acq-invoice-summary-count').innerHTML) + 1;
713 entryTbody = dojo.byId('acq-invoice-entry-tbody');
714 if(entryTemplate == null) {
715 entryTemplate = entryTbody.removeChild(dojo.byId('acq-invoice-entry-template'));
718 if(dojo.query('[lineitem=' + entry.lineitem() +']', entryTbody)[0])
719 // Is it ever valid to have multiple entries for 1 lineitem in a single invoice?
722 var row = entryTemplate.cloneNode(true);
723 row.setAttribute('lineitem', entry.lineitem());
724 row.setAttribute('entry_lineitem_row', entry.lineitem());
726 openils.acq.Lineitem.fetchAndRender(
727 entry.lineitem(), {},
730 entry.purchase_order(li.purchase_order());
731 nodeByName('title_details', row).innerHTML = html;
733 nodeByName('title_details', row).parentNode.id = 'li-title-ref-' + li.id();
734 console.log(dojo.byId('li-title-ref-' + li.id()));
736 updateReceiveLink(li);
738 // set some default values if otherwise unset
739 if (!invoicePane.getFieldValue('receiver')) {
740 invoicePane.setFieldValue('receiver', li.purchase_order().ordering_agency());
742 if (!invoicePane.getFieldValue('provider')) {
743 invoicePane.setFieldValue('provider', li.purchase_order().provider());
747 ['inv_item_count', 'phys_item_count', 'cost_billed', 'amount_paid'],
749 var dijitArgs = {required : true, constraints : {min: 0}, style : 'width:6em'};
750 if(field.match(/count/)) {
751 dijitArgs.style = 'width:4em;';
753 dijitArgs.style = 'width:9em;';
755 if(entry.isnew() && field == 'phys_item_count') {
756 // by default, attempt to pay for all non-canceled and as-of-yet-un-invoiced items
757 var count = Number(li.order_summary().item_count() || 0) -
758 Number(li.order_summary().cancel_count() || 0) -
759 Number(li.order_summary().invoice_count() || 0);
760 if(count < 0) count = 0;
761 dijitArgs.value = count;
766 new openils.widget.AutoFieldWidget({
770 dijitArgs : dijitArgs,
771 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
772 parentNode : nodeByName(field, row)
776 if(field == 'phys_item_count') {
777 dojo.connect(w, 'onChange',
779 // staff entered a higher number in the receive field than was originally ordered
780 // taking into account already invoiced items
781 var extra = Number(this.attr('value')) -
782 (Number(entry.lineitem().item_count()) - Number(entry.lineitem().order_summary().invoice_count()));
784 storeExtraCopies(entry, extra);
790 if(field == 'inv_item_count' || field == 'cost_billed') {
791 setPerCopyPrice(row, entry);
792 // update the per-copy count as invoice count and cost billed change
793 dojo.connect(w, 'onChange', function() { setPerCopyPrice(row, entry) } );
802 if (focusLineitem == li.id())
807 nodeByName('detach', row).onclick = function() {
808 var cost = widgetRegistry.acqie[entry.id()].cost_billed.getFormattedValue();
810 dojo.forEach(['isbn', 'upc', 'issn'],
812 var val = liMarcAttr(entry.lineitem(), ident);
813 if(val) idents.push(val);
817 var msg = dojo.string.substitute(
818 localeStrings.INVOICE_CONFIRM_ENTRY_DETACH, [
820 liMarcAttr(entry.lineitem(), 'title'),
821 liMarcAttr(entry.lineitem(), 'author'),
825 if(!confirm(msg)) return;
826 entryTbody.removeChild(row);
827 entry.isdeleted(true);
829 delete widgetRegistry.acqie[entry.id()];
833 entryTbody.appendChild(row);
836 function setPerCopyPrice(row, entry) {
837 var inv_w = widgetRegistry.acqie[entry.id()].inv_item_count;
838 var bill_w = widgetRegistry.acqie[entry.id()].cost_billed;
840 if (inv_w && bill_w) {
841 var invoiced = Number(inv_w.getFormattedValue());
842 var billed = Number(bill_w.getFormattedValue());
843 console.log(invoiced + ' : ' + billed);
845 nodeByName('amount_paid_per_copy', row).innerHTML = (billed / invoiced).toFixed(2);
847 nodeByName('amount_paid_per_copy', row).innerHTML = '0.00';
852 function liMarcAttr(lineitem, name) {
853 var attr = lineitem.attributes().filter(
856 attr.attr_type() == 'lineitem_marc_attr_definition' &&
857 attr.attr_name() == name)
861 return (attr) ? attr.attr_value() : '';
864 function saveChanges(args) {
866 createExtraCopies(function() { saveChangesPartTwo(args); });
869 // Define a helper function to 'unflesh' sub-objects from an fmclass object.
870 // 'this' specifies the object; the arguments specify a list of names of
874 dojo.forEach(arguments, function (n) {
876 if (_ !== null && typeof _ === 'object')
881 function saveChangesPartTwo(args) {
885 invoice.complete('f');
889 // Prepare an invoice for submission
891 invoice = new fieldmapper.acqinv();
894 invoice.ischanged(true); // for now, just always update
897 var e = invoicePane.mapValues(function (n, v) { invoice[n](v); });
898 if (e instanceof Error) {
904 invoice.complete('t');
907 // Prepare any charge items
908 var updateItems = [];
909 for(var id in widgetRegistry.acqii) {
910 var reg = widgetRegistry.acqii[id];
911 var item = reg._object;
912 if(item.ischanged() || item.isnew() || item.isdeleted()) {
913 updateItems.push(item);
914 if(item.isnew()) item.id(null);
915 for(var field in reg) {
916 if(field != '_object')
917 item[field]( reg[field].getFormattedValue() );
920 unflesh.call(item, 'purchase_order');
925 // Prepare any line items
926 var updateEntries = [];
927 for(var id in widgetRegistry.acqie) {
928 var reg = widgetRegistry.acqie[id];
929 var entry = reg._object;
930 if(entry.ischanged() || entry.isnew() || entry.isdeleted()) {
931 updateEntries.push(entry);
932 if(entry.isnew()) entry.id(null);
934 for(var field in reg) {
935 if(field != '_object')
936 entry[field]( reg[field].getFormattedValue() );
939 unflesh.call(entry, 'purchase_order', 'lineitem');
944 progressDialog.show(true);
945 fieldmapper.standardRequest(
946 ['open-ils.acq', 'open-ils.acq.invoice.update'],
948 params : [openils.User.authtoken, invoice, updateEntries, updateItems],
949 oncomplete : function(r) {
950 progressDialog.hide();
951 var invoice = openils.Util.readResponse(r);
954 return prorateInvoice(invoice);
956 location.href = oilsBasePath + '/acq/invoice/view?create=1';
958 location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
966 function prorateInvoice(invoice) {
967 if(!confirm(localeStrings.INVOICE_CONFIRM_PRORATE)) return;
968 progressDialog.show(true);
970 fieldmapper.standardRequest(
971 ['open-ils.acq', 'open-ils.acq.invoice.apply_prorate'],
973 params : [openils.User.authtoken, invoice.id()],
974 oncomplete : function(r) {
975 progressDialog.hide();
976 var invoice = openils.Util.readResponse(r);
978 location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
985 function storeExtraCopies(entry, numExtra) {
987 dojo.byId('acq-invoice-extra-copies-message').innerHTML =
988 dojo.string.substitute(
989 localeStrings.INVOICE_EXTRA_COPIES, [numExtra]);
992 addCopyHandler = dojo.connect(
996 extraCopies[entry.lineitem().id()] = {
998 fund : extraCopiesFund.widget.attr('value')
1000 extraItemsDialog.hide();
1001 dojo.disconnect(addCopyHandler);
1009 widgetRegistry.acqie[entry.id()].phys_item_count.widget.attr('value', '');
1010 extraItemsDialog.hide()
1014 extraItemsDialog.show();
1017 function createExtraCopies(oncomplete) {
1020 for(var liId in extraCopies) {
1021 var data = extraCopies[liId];
1022 for(var i = 0; i < data.numExtra; i++) {
1023 var lid = new fieldmapper.acqlid();
1026 lid.fund(data.fund);
1027 lid.recv_time('now');
1032 if(lids.length == 0)
1033 return oncomplete();
1035 fieldmapper.standardRequest(
1036 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1038 params : [openils.User.authtoken, lids, true],
1039 oncomplete : function(r) {
1040 if(openils.Util.readResponse(r))
1049 openils.Util.addOnLoad(init);