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 allResSelected = false;
415 function clearSearchResTable() {
416 allResSelected = false;
417 while (resultsTbody.childNodes[0])
418 resultsTbody.removeChild(resultsTbody.childNodes[0]);
421 function selectSearchResults() {
422 allResSelected = !allResSelected;
423 dojo.query('[name=search-results-checkbox]').forEach(
424 function(input) { input.checked = allResSelected });
427 function updateTotalCost() {
430 for(var id in widgetRegistry.acqii)
431 if(!widgetRegistry.acqii[id]._object.isdeleted())
432 totalCost += Number(widgetRegistry.acqii[id].cost_billed.getFormattedValue());
433 for(var id in widgetRegistry.acqie)
434 if(!widgetRegistry.acqie[id]._object.isdeleted())
435 totalCost += Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue());
436 totalInvoicedBox.innerHTML = totalCost.toFixed(2);
439 for(var id in widgetRegistry.acqii)
440 if(!widgetRegistry.acqii[id]._object.isdeleted())
441 totalPaid += Number(widgetRegistry.acqii[id].amount_paid.getFormattedValue());
442 for(var id in widgetRegistry.acqie)
443 if(!widgetRegistry.acqie[id]._object.isdeleted())
444 totalPaid += Number(widgetRegistry.acqie[id].amount_paid.getFormattedValue());
445 totalPaidBox.innerHTML = totalPaid.toFixed(2);
447 var buttonsDisabled = false;
449 if(totalPaid > totalCost || totalPaid < 0) {
450 openils.Util.addCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
451 invoiceSaveButton.attr('disabled', true);
452 invoiceProrateButton.attr('disabled', true);
453 buttonsDisabled = true;
455 openils.Util.removeCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
456 invoiceSaveButton.attr('disabled', false);
457 invoiceProrateButton.attr('disabled', false);
461 openils.Util.addCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
462 invoiceSaveButton.attr('disabled', true);
463 invoiceProrateButton.attr('disabled', true);
465 openils.Util.removeCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
466 if(!buttonsDisabled) {
467 invoiceSaveButton.attr('disabled', false);
468 invoiceProrateButton.attr('disabled', false);
472 if(totalPaid == totalCost) { // XXX: too rigid?
473 invoiceCloseButton.attr('disabled', false);
475 invoiceCloseButton.attr('disabled', true);
478 balanceOwedBox.innerHTML = (totalCost - totalPaid).toFixed(2);
480 updateExpectedCost();
484 function registerWidget(obj, field, widget, callback) {
485 var blob = widgetRegistry[obj.classname];
487 blob[obj.id()] = {_object : obj};
488 blob[obj.id()][field] = widget;
491 dojo.connect(w, 'onChange',
497 if(callback) callback(w, ww);
503 function addInvoiceItem(item) {
504 itemTbody = dojo.byId('acq-invoice-item-tbody');
505 if(itemTemplate == null) {
506 itemTemplate = itemTbody.removeChild(dojo.byId('acq-invoice-item-template'));
509 var row = itemTemplate.cloneNode(true);
510 var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
513 ['title', 'author', 'cost_billed', 'amount_paid'],
517 if(field == 'title' || field == 'author') {
518 //args = {style : 'width:10em'};
519 } else if(field == 'cost_billed' || field == 'amount_paid') {
520 args = {required : true, style : 'width: 8em'};
526 new openils.widget.AutoFieldWidget({
530 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
532 parentNode : nodeByName(field, row)
539 /* ----------- fund -------------- */
544 labelFormat : fundLabelFormat,
545 searchFormat : fundSearchFormat,
546 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
547 dijitArgs : {required : true},
548 parentNode : nodeByName('fund', row)
551 if(item.fund_debit()) {
552 fundArgs.searchFilter = {'-or' : [{active : 't'}, {id : item.fund()}]};
554 fundArgs.searchFilter = {active : 't'}
555 if(itemType && openils.Util.isTrue(itemType.prorate()))
556 fundArgs.dijitArgs = {disabled : true};
559 var fundWidget = new openils.widget.AutoFieldWidget(fundArgs);
560 registerWidget(item, 'fund', fundWidget);
562 /* ---------- inv_item_type ------------- */
566 // read-only item view for items that were the result of a po-item
567 var po = item.purchase_order();
568 var po_item = item.po_item();
569 var node = nodeByName('inv_item_type', row);
570 var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
571 orderDate = (!po.order_date()) ? '' :
572 dojo.date.locale.format(dojo.date.stamp.fromISOString(po.order_date()), {selector:'date'});
574 node.innerHTML = dojo.string.substitute(
575 localeStrings.INVOICE_ITEM_PO_DETAILS,
582 po_item.estimated_cost()
591 new openils.widget.AutoFieldWidget({
593 fmField : 'inv_item_type',
594 parentNode : nodeByName('inv_item_type', row),
595 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
596 dijitArgs : {required : true}
599 // When the inv_item_type is set to prorate=true, don't allow the user the edit the fund
600 // since this charge will be prorated against (potentially) multiple funds
601 dojo.connect(w, 'onChange',
603 if(!item.fund_debit()) {
604 var itemType = itemTypes.filter(function(t) { return (t.code() == w.attr('value')) })[0];
605 if(!itemType) return;
606 if(openils.Util.isTrue(itemType.prorate())) {
607 fundWidget.widget.attr('disabled', true);
608 fundWidget.widget.attr('value', '');
610 fundWidget.widget.attr('disabled', false);
619 nodeByName('delete', row).onclick = function() {
620 var cost = widgetRegistry.acqii[item.id()].cost_billed.getFormattedValue();
621 var msg = dojo.string.substitute(
622 localeStrings.INVOICE_CONFIRM_ITEM_DELETE, [
624 widgetRegistry.acqii[item.id()].inv_item_type.getFormattedValue() || ''
627 if(!confirm(msg)) return;
628 itemTbody.removeChild(row);
629 item.isdeleted(true);
631 delete widgetRegistry.acqii[item.id()];
635 itemTbody.appendChild(row);
639 function updateReceiveLink(li) {
641 return; /* can't do this with unsaved invoices */
643 var link = dojo.byId("acq-view-invoice-receive-link");
644 if (link.onclick) return; /* only need to do this once */
646 /* don't do this if there's nothing receivable on the lineitem */
647 if (li.order_summary().recv_count() + li.order_summary().cancel_count() >=
648 li.order_summary().item_count())
651 openils.Util.show("acq-view-invoice-receive");
652 link.onclick = function() { location.href = oilsBasePath + '/acq/invoice/receive/' + invoiceId; };
656 * Ensures focusLineitem is in view and causes a brief
657 * border around the lineitem to come to life then fade.
660 if (!focusLineitem) return;
662 // set during addLineitem()
663 var node = dojo.byId('li-title-ref-' + focusLineitem);
665 console.log('focus: li-title-ref-' + focusLineitem + ' : ' + node);
667 // LI may not yet be rendered
670 console.log('focusing ' + focusLineitem);
672 // prevent numerous re-focuses
673 focusLineitem = null;
675 // causes the full row to be visible
676 dijit.scrollIntoView(node);
678 dojo.require('dojox.fx');
682 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
688 // expected cost is totalCostInvoiced + totalCostNotYetInvoiced
689 function updateExpectedCost() {
691 var cost = Number(totalInvoicedBox.innerHTML || 0);
693 // for any LI's that are not yet billed (i.e. filled in)
694 // use the total expected cost for that lineitem.
695 for(var id in widgetRegistry.acqie) {
696 var entry = widgetRegistry.acqie[id]._object;
697 if(!entry.isdeleted()) {
698 if (Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue()) == 0) {
699 var li = entry.lineitem();
701 Number(li.order_summary().estimated_amount()) -
702 Number(li.order_summary().paid_amount());
707 dojo.byId('acq-invoice-summary-cost').innerHTML = cost.toFixed(2);
710 var invoicEntryWidgets = {};
711 function addInvoiceEntry(entry) {
712 console.log('Adding new entry for lineitem ' + entry.lineitem());
714 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-header'), 'hidden');
715 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-thead'), 'hidden');
716 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-tbody'), 'hidden');
718 dojo.byId('acq-invoice-summary-count').innerHTML =
719 Number(dojo.byId('acq-invoice-summary-count').innerHTML) + 1;
721 entryTbody = dojo.byId('acq-invoice-entry-tbody');
722 if(entryTemplate == null) {
723 entryTemplate = entryTbody.removeChild(dojo.byId('acq-invoice-entry-template'));
726 if(dojo.query('[lineitem=' + entry.lineitem() +']', entryTbody)[0])
727 // Is it ever valid to have multiple entries for 1 lineitem in a single invoice?
730 var row = entryTemplate.cloneNode(true);
731 row.setAttribute('lineitem', entry.lineitem());
732 row.setAttribute('entry_lineitem_row', entry.lineitem());
734 openils.acq.Lineitem.fetchAndRender(
735 entry.lineitem(), {},
738 entry.purchase_order(li.purchase_order());
739 nodeByName('title_details', row).innerHTML = html;
741 nodeByName('title_details', row).parentNode.id = 'li-title-ref-' + li.id();
742 console.log(dojo.byId('li-title-ref-' + li.id()));
744 updateReceiveLink(li);
746 // set some default values if otherwise unset
747 if (!invoicePane.getFieldValue('receiver')) {
748 invoicePane.setFieldValue('receiver', li.purchase_order().ordering_agency());
750 if (!invoicePane.getFieldValue('provider')) {
751 invoicePane.setFieldValue('provider', li.purchase_order().provider());
755 ['inv_item_count', 'phys_item_count', 'cost_billed', 'amount_paid'],
757 var dijitArgs = {required : true, constraints : {min: 0}, style : 'width:6em'};
758 if(field.match(/count/)) {
759 dijitArgs.style = 'width:4em;';
761 dijitArgs.style = 'width:9em;';
763 if(entry.isnew() && field == 'phys_item_count') {
764 // by default, attempt to pay for all non-canceled and as-of-yet-un-invoiced items
765 var count = Number(li.order_summary().item_count() || 0) -
766 Number(li.order_summary().cancel_count() || 0) -
767 Number(li.order_summary().invoice_count() || 0);
768 if(count < 0) count = 0;
769 dijitArgs.value = count;
774 new openils.widget.AutoFieldWidget({
778 dijitArgs : dijitArgs,
779 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
780 parentNode : nodeByName(field, row)
784 if(field == 'phys_item_count') {
785 dojo.connect(w, 'onChange',
787 // staff entered a higher number in the receive field than was originally ordered
788 // taking into account already invoiced items
789 var extra = Number(this.attr('value')) -
790 (Number(entry.lineitem().item_count()) - Number(entry.lineitem().order_summary().invoice_count()));
792 storeExtraCopies(entry, extra);
798 if(field == 'inv_item_count' || field == 'cost_billed') {
799 setPerCopyPrice(row, entry);
800 // update the per-copy count as invoice count and cost billed change
801 dojo.connect(w, 'onChange', function() { setPerCopyPrice(row, entry) } );
810 if (focusLineitem == li.id())
815 nodeByName('detach', row).onclick = function() {
816 var cost = widgetRegistry.acqie[entry.id()].cost_billed.getFormattedValue();
818 dojo.forEach(['isbn', 'upc', 'issn'],
820 var val = liMarcAttr(entry.lineitem(), ident);
821 if(val) idents.push(val);
825 var msg = dojo.string.substitute(
826 localeStrings.INVOICE_CONFIRM_ENTRY_DETACH, [
828 liMarcAttr(entry.lineitem(), 'title'),
829 liMarcAttr(entry.lineitem(), 'author'),
833 if(!confirm(msg)) return;
834 entryTbody.removeChild(row);
835 entry.isdeleted(true);
837 delete widgetRegistry.acqie[entry.id()];
841 entryTbody.appendChild(row);
844 function setPerCopyPrice(row, entry) {
845 var inv_w = widgetRegistry.acqie[entry.id()].inv_item_count;
846 var bill_w = widgetRegistry.acqie[entry.id()].cost_billed;
848 if (inv_w && bill_w) {
849 var invoiced = Number(inv_w.getFormattedValue());
850 var billed = Number(bill_w.getFormattedValue());
851 console.log(invoiced + ' : ' + billed);
853 nodeByName('amount_paid_per_copy', row).innerHTML = (billed / invoiced).toFixed(2);
855 nodeByName('amount_paid_per_copy', row).innerHTML = '0.00';
860 function liMarcAttr(lineitem, name) {
861 var attr = lineitem.attributes().filter(
864 attr.attr_type() == 'lineitem_marc_attr_definition' &&
865 attr.attr_name() == name)
869 return (attr) ? attr.attr_value() : '';
872 function saveChanges(args) {
874 createExtraCopies(function() { saveChangesPartTwo(args); });
877 // Define a helper function to 'unflesh' sub-objects from an fmclass object.
878 // 'this' specifies the object; the arguments specify a list of names of
882 dojo.forEach(arguments, function (n) {
884 if (_ !== null && typeof _ === 'object')
889 function saveChangesPartTwo(args) {
893 invoice.complete('f');
897 // Prepare an invoice for submission
899 invoice = new fieldmapper.acqinv();
902 invoice.ischanged(true); // for now, just always update
905 var e = invoicePane.mapValues(function (n, v) { invoice[n](v); });
906 if (e instanceof Error) {
912 invoice.complete('t');
915 // Prepare any charge items
916 var updateItems = [];
917 for(var id in widgetRegistry.acqii) {
918 var reg = widgetRegistry.acqii[id];
919 var item = reg._object;
920 if(item.ischanged() || item.isnew() || item.isdeleted()) {
921 updateItems.push(item);
922 if(item.isnew()) item.id(null);
923 for(var field in reg) {
924 if(field != '_object')
925 item[field]( reg[field].getFormattedValue() );
928 unflesh.call(item, 'purchase_order');
933 // Prepare any line items
934 var updateEntries = [];
935 for(var id in widgetRegistry.acqie) {
936 var reg = widgetRegistry.acqie[id];
937 var entry = reg._object;
938 if(entry.ischanged() || entry.isnew() || entry.isdeleted()) {
939 updateEntries.push(entry);
940 if(entry.isnew()) entry.id(null);
942 for(var field in reg) {
943 if(field != '_object')
944 entry[field]( reg[field].getFormattedValue() );
947 unflesh.call(entry, 'purchase_order', 'lineitem');
952 progressDialog.show(true);
953 fieldmapper.standardRequest(
954 ['open-ils.acq', 'open-ils.acq.invoice.update'],
956 params : [openils.User.authtoken, invoice, updateEntries, updateItems],
957 oncomplete : function(r) {
958 progressDialog.hide();
959 var invoice = openils.Util.readResponse(r);
962 return prorateInvoice(invoice);
964 location.href = oilsBasePath + '/acq/invoice/view?create=1';
966 location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
974 function prorateInvoice(invoice) {
975 if(!confirm(localeStrings.INVOICE_CONFIRM_PRORATE)) return;
976 progressDialog.show(true);
978 fieldmapper.standardRequest(
979 ['open-ils.acq', 'open-ils.acq.invoice.apply_prorate'],
981 params : [openils.User.authtoken, invoice.id()],
982 oncomplete : function(r) {
983 progressDialog.hide();
984 var invoice = openils.Util.readResponse(r);
986 location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
993 function storeExtraCopies(entry, numExtra) {
995 dojo.byId('acq-invoice-extra-copies-message').innerHTML =
996 dojo.string.substitute(
997 localeStrings.INVOICE_EXTRA_COPIES, [numExtra]);
1000 addCopyHandler = dojo.connect(
1004 extraCopies[entry.lineitem().id()] = {
1005 numExtra : numExtra,
1006 fund : extraCopiesFund.widget.attr('value')
1008 extraItemsDialog.hide();
1009 dojo.disconnect(addCopyHandler);
1017 widgetRegistry.acqie[entry.id()].phys_item_count.widget.attr('value', '');
1018 extraItemsDialog.hide()
1022 extraItemsDialog.show();
1025 function validateInvIdent(inv_ident, provider, receiver) {
1026 if (!(inv_ident && provider && receiver)) {
1027 console.info("not enough information to pre-validate inv_ident");
1031 openils.Util.show("ident-validation-spinner", "inline");
1032 var pcrud = new openils.PermaCrud();
1034 "acqinv", {"inv_ident": inv_ident, "provider": provider}, {
1035 "oncomplete": function(r) {
1036 openils.Util.hide("ident-validation-spinner");
1038 /* This could throw an event about the user not having perms,
1039 * but in such a case the whole interface is already busted
1041 r = openils.Util.readResponse(r);
1043 var w = invoicePane.getFieldWidget("inv_ident").widget;
1045 alert(localeStrings.INVOICE_IDENT_COLLIDE);
1046 w.validator = function() { return false; };
1049 w.validator = function() { return true; };
1059 function drawInvoicePane(parentNode, inv, args) {
1066 recv_date : {widgetValue : dojo.date.stamp.toISOString(new Date())},
1067 //receiver : {widgetValue : openils.User.user.ws_ou()},
1070 "onChange": function(val) {
1072 invoicePane && invoicePane.getFieldValue("inv_ident"),
1073 invoicePane && invoicePane.getFieldValue("provider"),
1079 recv_method : {widgetValue : 'PPR'}
1083 dojo.mixin(override, {
1086 store_options : { base_filter : { active :"t" } },
1087 onChange : function(val) {
1088 pane.setFieldValue('shipper', val);
1090 invoicePane && invoicePane.getFieldValue("inv_ident"),
1092 invoicePane && invoicePane.getFieldValue("receiver")
1097 shipper : { dijitArgs : { store_options : { base_filter : { active :"t" } } } }
1100 for(var field in args) {
1101 override[field] = {widgetValue : args[field]};
1104 // push the name of the invoice into the name display field after update
1105 override.inv_ident = dojo.mixin(
1107 {dijitArgs : {onChange :
1111 invoicePane && invoicePane.getFieldValue("provider"),
1112 invoicePane && invoicePane.getFieldValue("receiver")
1115 if (dojo.byId('acq-invoice-summary-name'))
1116 dojo.byId('acq-invoice-summary-name').innerHTML = newVal;
1122 pane = new openils.widget.EditPane({
1126 mode : (inv) ? 'edit' : 'create',
1127 hideActionButtons : true,
1128 overrideWidgetArgs : override,
1129 readOnly : (inv) && openils.Util.isTrue(inv.complete()),
1144 suppressFields : ['id', 'complete']
1148 parentNode.appendChild(pane.domNode);
1153 function createExtraCopies(oncomplete) {
1156 for(var liId in extraCopies) {
1157 var data = extraCopies[liId];
1158 for(var i = 0; i < data.numExtra; i++) {
1159 var lid = new fieldmapper.acqlid();
1162 lid.fund(data.fund);
1163 lid.recv_time('now');
1168 if(lids.length == 0)
1169 return oncomplete();
1171 fieldmapper.standardRequest(
1172 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1174 params : [openils.User.authtoken, lids, true],
1175 oncomplete : function(r) {
1176 if(openils.Util.readResponse(r))
1185 openils.Util.addOnLoad(init);