1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dojo.cookie');
4 dojo.require('dijit.form.CheckBox');
5 dojo.require('dijit.form.Button');
6 dojo.require('dijit.form.CurrencyTextBox');
7 dojo.require('dijit.form.NumberTextBox');
8 dojo.require('openils.User');
9 dojo.require('openils.Util');
10 dojo.require('openils.CGI');
11 dojo.require('openils.PermaCrud');
12 dojo.require('openils.widget.EditPane');
13 dojo.require('openils.widget.AutoFieldWidget');
14 dojo.require('openils.widget.ProgressDialog');
15 dojo.require('openils.acq.Lineitem');
16 dojo.require('openils.XUL');
18 dojo.requireLocalization('openils.acq', 'acq');
19 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
21 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
22 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
24 var cgi = new openils.CGI();
25 var pcrud = new openils.PermaCrud();
40 var widgetRegistry = {acqie : {}, acqii : {}};
42 var searchInitDone = false;
46 function nodeByName(name, context) {
47 return dojo.query('[name='+name+']', context)[0];
52 attachLi = cgi.param('attach_li') || [];
53 if (!dojo.isArray(attachLi))
54 attachLi = [attachLi];
56 attachPo = cgi.param('attach_po') || [];
57 if (!dojo.isArray(attachPo))
58 attachPo = [attachPo];
60 focusLineitem = new openils.CGI().param('focus_li');
62 totalInvoicedBox = dojo.byId('acq-total-invoiced-box');
63 totalPaidBox = dojo.byId('acq-total-paid-box');
64 balanceOwedBox = dojo.byId('acq-total-balance-box');
66 itemTypes = pcrud.retrieveAll('aiit');
68 dojo.byId('acq-invoice-summary-toggle-off').onclick = function() {
69 openils.Util.hide(dojo.byId('acq-invoice-summary'));
70 openils.Util.show(dojo.byId('acq-invoice-summary-small'));
73 dojo.byId('acq-invoice-summary-toggle-on').onclick = function() {
74 openils.Util.show(dojo.byId('acq-invoice-summary'));
75 openils.Util.hide(dojo.byId('acq-invoice-summary-small'));
78 if(cgi.param('create')) {
81 // show summary info by default for new invoices
82 dojo.byId('acq-invoice-summary-toggle-on').onclick();
85 dojo.byId('acq-invoice-summary-toggle-off').onclick();
86 fieldmapper.standardRequest(
87 ['open-ils.acq', 'open-ils.acq.invoice.retrieve.authoritative'],
89 params : [openils.User.authtoken, invoiceId],
90 oncomplete : function(r) {
91 invoice = openils.Util.readResponse(r);
98 extraCopiesFund = new openils.widget.AutoFieldWidget({
101 searchFilter : {active : 't'},
102 labelFormat : fundLabelFormat,
103 searchFormat : fundSearchFormat,
104 dijitArgs : {required : true},
105 parentNode : dojo.byId('acq-invoice-extra-copies-fund')
107 extraCopiesFund.build();
110 function renderInvoice() {
112 // in create mode, let the LI or PO render the invoice with seed data
113 if( !(cgi.param('create') && (attachPo.length || attachLi.length)) ) {
114 invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), invoice);
117 dojo.byId('acq-invoice-new-item').onclick = function() {
118 var item = new fieldmapper.acqii();
119 item.id(virtualId--);
121 addInvoiceItem(item);
126 if(invoice && openils.Util.isTrue(invoice.complete())) {
128 dojo.forEach( // hide widgets that should not be visible for a completed invoice
129 dojo.query('.hide-complete'),
130 function(node) { openils.Util.hide(node); }
133 new openils.User().getPermOrgList(
134 'ACQ_INVOICE_REOPEN',
136 if(orgs.indexOf(invoice.receiver()) >= 0)
137 openils.Util.show('acq-invoice-reopen-button-wrapper', 'inline');
144 // display items and entries in ID order
145 // which effectively equates to add order.
146 function idsort(a, b) { return a.id() < b.id() ? -1 : 1 }
150 invoice.items().sort(idsort),
152 addInvoiceItem(item);
157 invoice.entries().sort(idsort),
159 addInvoiceEntry(entry);
164 if(attachLi.length) doAttachLi();
165 if(attachPo.length) doAttachPo(0);
168 function doAttachLi(skipInit) {
170 //var invoiceArgs = {provider : lineitem.provider(), shipper : lineitem.provider()};
171 if(cgi.param('create') && !skipInit) {
173 // use the first LI in the list to determine the default provider
174 fieldmapper.standardRequest(
175 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
177 params : [openils.User.authtoken, attachLi[0], {clear_marc:1}],
178 oncomplete : function(r) {
179 var li = openils.Util.readResponse(r);
180 invoicePane = drawInvoicePane(
181 dojo.byId('acq-view-invoice-div'), null,
182 {provider : li.provider(), shipper : li.provider()}
189 dojo.forEach(attachLi,
191 var entry = new fieldmapper.acqie();
192 entry.id(virtualId--);
195 addInvoiceEntry(entry);
200 function doAttachPo(idx) {
202 if (idx == attachPo.length) return;
203 var poId = attachPo[idx];
205 fieldmapper.standardRequest(
206 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
209 openils.User.authtoken, poId,
210 {flesh_lineitem_ids : true, flesh_po_items : true}
212 oncomplete: function(r) {
213 var po = openils.Util.readResponse(r);
215 if(cgi.param('create') && idx == 0) {
216 // render the invoice using some seed data from the first PO
217 var invoiceArgs = {provider : po.provider(), shipper : po.provider()};
218 invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), null, invoiceArgs);
221 dojo.forEach(po.lineitems(),
223 var entry = new fieldmapper.acqie();
224 entry.id(virtualId--);
226 entry.lineitem(lineitem);
227 entry.purchase_order(po);
228 addInvoiceEntry(entry);
232 dojo.forEach(po.po_items(),
234 var item = new fieldmapper.acqii();
235 item.id(virtualId--);
237 item.fund(poItem.fund());
238 item.title(poItem.title());
239 item.author(poItem.author());
240 item.note(poItem.note());
241 item.inv_item_type(poItem.inv_item_type());
242 item.purchase_order(po);
243 item.po_item(poItem);
244 addInvoiceItem(item);
255 var cookieUriSSL, cookieSvc, cookieMgr;
257 function performSearch(pageDir, clearFirst) {
259 clearSearchResTable();
261 var searchObject = termManager.buildSearchObject();
263 if (openils.XUL.isXUL()) {
265 cookieSvc.setCookieString(cookieUriSSL, null,
266 "invs=" + base64Encode(searchObject) + ';max-age=2592000', null);
268 cookieSvc.setCookieString(cookieUriSSL, null,
269 "invc=" + dojo.byId("acq-unified-conjunction").getValue() +
270 ';max-age=2592000', null);
274 dojo.cookie('invs', base64Encode(searchObject));
275 dojo.cookie('invc', dojo.byId("acq-unified-conjunction").getValue());
278 if (pageDir == 0) { // new search
279 resultsLoader.displayOffset = 0;
281 resultsLoader.displayOffset += pageDir * resultsLoader.displayLimit;
284 if (resultsLoader.displayOffset == 0) {
285 openils.Util.hide('acq-inv-search-prev');
287 openils.Util.show('acq-inv-search-prev', 'inline');
290 if (dojo.byId('acq-invoice-search-limit-invoiceable').checked) {
291 if (!searchObject.jub)
292 searchObject.jub = [];
294 // exclude lineitems that are "cancelled" (sidebar: 'Mericans spell it 'canceled')
295 searchObject.jub.push({state : 'cancelled', '__not' : true});
297 // exclude lineitems already linked to this invoice
298 if (invoice && invoice.id() > 0) {
299 if (!searchObject.acqinv)
300 searchObject.acqinv = [];
301 searchObject.acqinv.push({id : invoice.id(), '__not' : true});
304 // limit to lineitems that have invoiceable copies
305 searchObject.acqlisumi = [{item_count : 1, '_gte' : true}];
307 // limit to provider if a provider is selected
308 var provider = invoicePane.getFieldValue('provider');
310 if (!searchObject.jub.filter(function(i) { return i.provider != null }).length)
311 searchObject.jub.push({provider : provider});
315 if (dojo.byId('acq-invoice-search-sort-title').checked) {
316 uriManager.order_by =
317 [ {"class": "acqlia", "field":"attr_value", "transform":"first"} ];
320 resultsLoader.lastSearch = searchObject;
321 resultManager.go(searchObject)
322 console.log('Lineitem Search: ' + js2JSON(searchObject));
323 focusLastSearchInput();
327 function renderUnifiedSearch() {
329 if (!searchInitDone) {
331 searchInitDone = true;
332 termManager = new TermManager();
333 resultManager = new ResultManager();
334 resultsLoader = new searchResultsLoader();
335 uriManager = new URIManager();
337 // define custom lineitem result handler
338 resultManager.result_types = {
340 "search_options": { "id_list": true },
341 "revealer": function() { },
342 "finisher": function() {
343 resultsLoader.batch_length = resultManager.count_results;
345 "adder": function(li) {
346 resultsLoader.addLineitem(li);
348 "interface": resultsLoader
351 "revealer": function() { }
356 resultManager.no_results_popup = true;
357 resultManager.submitter = smartSearchSubmitter;
359 var searchObject, searchConjunction;
361 if (openils.XUL.isXUL()) {
365 var ios = Components.classes["@mozilla.org/network/io-service;1"]
366 .getService(Components.interfaces.nsIIOService);
368 cookieUriSSL = ios.newURI("https://" + location.hostname, null, null);
370 cookieSvc = Components.classes["@mozilla.org/cookieService;1"]
371 .getService(Components.interfaces.nsICookieService);
374 cookieManager = Components.classes["@mozilla.org/cookiemanager;1"]
375 .getService(Components.interfaces.nsICookieManager);
378 var iter = cookieManager.enumerator;
379 while (iter.hasMoreElements()) {
380 var cookie = iter.getNext();
381 if (cookie instanceof Components.interfaces.nsICookie) {
382 if (cookie.name == 'invs')
383 searchObject = cookie.value;
384 if (cookie.name == 'invc')
385 searchConjunction = cookie.value;
390 // useful for web-based testing
391 searchObject = dojo.cookie('invs');
392 searchConjunction = dojo.cookie('invc');
397 // if there is a search object cookie, populate the search form
398 termManager.reflect(base64Decode(searchObject));
399 dojo.byId("acq-unified-conjunction").setValue(searchConjunction);
402 console.log('adding row');
403 termManager.addRow();
407 dojo.addClass(dojo.byId('oils-acq-invoice-table'), 'hidden');
408 dojo.removeClass(dojo.byId('oils-acq-invoice-search'), 'hidden');
409 focusLastSearchInput();
412 function focusLastSearchInput() {
413 // TODO: see about making this better and moving it into search/unified.js
414 var wnodes = dojo.query('[name=widget]');
415 var inputNode = wnodes.item(wnodes.length - 1).firstChild;
425 var resultsTbody, resultsRow;
426 function searchResultsLoader() {
427 this.displayOffset = 0;
428 this.displayLimit = 10;
431 resultsTbody = dojo.byId('acq-invoice-search-results-tbody');
432 resultsRow = resultsTbody.removeChild(dojo.byId('acq-invoice-search-results-tr'));
435 this.addLineitem = function(li_id) {
436 console.log('Adding search result lineitem ' + li_id);
437 var row = resultsRow.cloneNode(true);
438 resultsTbody.appendChild(row);
439 var checkbox = dojo.query('[name=search-results-checkbox]', row)[0];
440 checkbox.setAttribute('lineitem', li_id);
442 // this lineitem is already part of the invoice
443 if (dojo.query('[entry_lineitem_row=' + li_id + ']')[0]) {
444 checkbox.disabled = true;
445 dojo.addClass(checkbox.parentNode, 'search-results-already-invoiced');
448 openils.acq.Lineitem.fetchAndRender(
451 dojo.query('[name=search-results-content-div]', row)[0].innerHTML = html;
457 function addSelectedToInvoice() {
458 var inputs = dojo.query('[name=search-results-checkbox]');
462 if (checkbox.checked) {
463 attachLi.push(checkbox.getAttribute('lineitem'));
464 checkbox.disabled = true;
465 checkbox.checked = false;
466 dojo.addClass(checkbox.parentNode, 'search-results-already-invoiced');
473 allResSelected = false;
474 function clearSearchResTable() {
475 allResSelected = false;
476 while (resultsTbody.childNodes[0])
477 resultsTbody.removeChild(resultsTbody.childNodes[0]);
480 function selectSearchResults() {
481 allResSelected = !allResSelected;
482 dojo.query('[name=search-results-checkbox]').forEach(
483 function(input) { input.checked = allResSelected });
486 function updateTotalCost() {
489 for(var id in widgetRegistry.acqii)
490 if(!widgetRegistry.acqii[id]._object.isdeleted())
491 totalCost += Number(widgetRegistry.acqii[id].cost_billed.getFormattedValue());
492 for(var id in widgetRegistry.acqie)
493 if(!widgetRegistry.acqie[id]._object.isdeleted())
494 totalCost += Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue());
495 totalInvoicedBox.innerHTML = totalCost.toFixed(2);
498 for(var id in widgetRegistry.acqii)
499 if(!widgetRegistry.acqii[id]._object.isdeleted())
500 totalPaid += Number(widgetRegistry.acqii[id].amount_paid.getFormattedValue());
501 for(var id in widgetRegistry.acqie)
502 if(!widgetRegistry.acqie[id]._object.isdeleted())
503 totalPaid += Number(widgetRegistry.acqie[id].amount_paid.getFormattedValue());
504 totalPaidBox.innerHTML = totalPaid.toFixed(2);
506 var buttonsDisabled = false;
508 if(totalPaid > totalCost || totalPaid < 0) {
509 openils.Util.addCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
510 invoiceSaveButton.attr('disabled', true);
511 invoiceProrateButton.attr('disabled', true);
512 buttonsDisabled = true;
514 openils.Util.removeCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
515 invoiceSaveButton.attr('disabled', false);
516 invoiceProrateButton.attr('disabled', false);
520 openils.Util.addCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
521 invoiceSaveButton.attr('disabled', true);
522 invoiceProrateButton.attr('disabled', true);
524 openils.Util.removeCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
525 if(!buttonsDisabled) {
526 invoiceSaveButton.attr('disabled', false);
527 invoiceProrateButton.attr('disabled', false);
531 if(totalPaid == totalCost) { // XXX: too rigid?
532 invoiceCloseButton.attr('disabled', false);
534 invoiceCloseButton.attr('disabled', true);
537 balanceOwedBox.innerHTML = (totalCost - totalPaid).toFixed(2);
539 updateExpectedCost();
543 function registerWidget(obj, field, widget, callback) {
544 var blob = widgetRegistry[obj.classname];
546 blob[obj.id()] = {_object : obj};
547 blob[obj.id()][field] = widget;
550 dojo.connect(w, 'onChange',
556 if(callback) callback(w, ww);
562 function addInvoiceItem(item) {
563 itemTbody = dojo.byId('acq-invoice-item-tbody');
564 if(itemTemplate == null) {
565 itemTemplate = itemTbody.removeChild(dojo.byId('acq-invoice-item-template'));
568 var row = itemTemplate.cloneNode(true);
569 var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
572 ['title', 'author', 'cost_billed', 'amount_paid'],
576 if(field == 'title' || field == 'author') {
577 //args = {style : 'width:10em'};
578 } else if(field == 'cost_billed' || field == 'amount_paid') {
579 args = {required : true, style : 'width: 8em'};
585 new openils.widget.AutoFieldWidget({
589 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
591 parentNode : nodeByName(field, row)
598 /* ----------- fund -------------- */
603 labelFormat : fundLabelFormat,
604 searchFormat : fundSearchFormat,
605 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
606 dijitArgs : {required : true},
607 parentNode : nodeByName('fund', row)
610 if(item.fund_debit()) {
611 fundArgs.searchFilter = {'-or' : [{active : 't'}, {id : item.fund()}]};
613 fundArgs.searchFilter = {active : 't'}
614 if(itemType && openils.Util.isTrue(itemType.prorate()))
615 fundArgs.dijitArgs = {disabled : true};
618 var fundWidget = new openils.widget.AutoFieldWidget(fundArgs);
619 registerWidget(item, 'fund', fundWidget);
621 /* ---------- inv_item_type ------------- */
625 // read-only item view for items that were the result of a po-item
626 var po = item.purchase_order();
627 var po_item = item.po_item();
628 var node = nodeByName('inv_item_type', row);
629 var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
630 orderDate = (!po.order_date()) ? '' :
631 dojo.date.locale.format(dojo.date.stamp.fromISOString(po.order_date()), {selector:'date'});
633 node.innerHTML = dojo.string.substitute(
634 localeStrings.INVOICE_ITEM_PO_DETAILS,
641 po_item.estimated_cost()
650 new openils.widget.AutoFieldWidget({
652 fmField : 'inv_item_type',
653 parentNode : nodeByName('inv_item_type', row),
654 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
655 dijitArgs : {required : true}
658 // When the inv_item_type is set to prorate=true, don't allow the user the edit the fund
659 // since this charge will be prorated against (potentially) multiple funds
660 dojo.connect(w, 'onChange',
662 if(!item.fund_debit()) {
663 var itemType = itemTypes.filter(function(t) { return (t.code() == w.attr('value')) })[0];
664 if(!itemType) return;
665 if(openils.Util.isTrue(itemType.prorate())) {
666 fundWidget.widget.attr('disabled', true);
667 fundWidget.widget.attr('value', '');
669 fundWidget.widget.attr('disabled', false);
678 nodeByName('delete', row).onclick = function() {
679 var cost = widgetRegistry.acqii[item.id()].cost_billed.getFormattedValue();
680 var msg = dojo.string.substitute(
681 localeStrings.INVOICE_CONFIRM_ITEM_DELETE, [
683 widgetRegistry.acqii[item.id()].inv_item_type.getFormattedValue() || ''
686 if(!confirm(msg)) return;
687 itemTbody.removeChild(row);
688 item.isdeleted(true);
690 delete widgetRegistry.acqii[item.id()];
694 itemTbody.appendChild(row);
698 function updateReceiveLink(li) {
700 return; /* can't do this with unsaved invoices */
702 var link = dojo.byId("acq-view-invoice-receive-link");
703 if (link.onclick) return; /* only need to do this once */
705 /* don't do this if there's nothing receivable on the lineitem */
706 if (li.order_summary().recv_count() + li.order_summary().cancel_count() >=
707 li.order_summary().item_count())
710 openils.Util.show("acq-view-invoice-receive");
711 link.onclick = function() { location.href = oilsBasePath + '/acq/invoice/receive/' + invoiceId; };
715 * Ensures focusLineitem is in view and causes a brief
716 * border around the lineitem to come to life then fade.
719 if (!focusLineitem) return;
721 // set during addLineitem()
722 var node = dojo.byId('li-title-ref-' + focusLineitem);
724 console.log('focus: li-title-ref-' + focusLineitem + ' : ' + node);
726 // LI may not yet be rendered
729 console.log('focusing ' + focusLineitem);
731 // prevent numerous re-focuses
732 focusLineitem = null;
734 // causes the full row to be visible
735 dijit.scrollIntoView(node);
737 dojo.require('dojox.fx');
741 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
747 // expected cost is totalCostInvoiced + totalCostNotYetInvoiced
748 function updateExpectedCost() {
750 var cost = Number(totalInvoicedBox.innerHTML || 0);
752 // for any LI's that are not yet billed (i.e. filled in)
753 // use the total expected cost for that lineitem.
754 for(var id in widgetRegistry.acqie) {
755 var entry = widgetRegistry.acqie[id]._object;
756 if(!entry.isdeleted()) {
757 if (Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue()) == 0) {
758 var li = entry.lineitem();
760 Number(li.order_summary().estimated_amount()) -
761 Number(li.order_summary().paid_amount());
766 dojo.byId('acq-invoice-summary-cost').innerHTML = cost.toFixed(2);
769 var invoicEntryWidgets = {};
770 function addInvoiceEntry(entry) {
771 console.log('Adding new entry for lineitem ' + entry.lineitem());
773 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-header'), 'hidden');
774 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-thead'), 'hidden');
775 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-tbody'), 'hidden');
777 dojo.byId('acq-invoice-summary-count').innerHTML =
778 Number(dojo.byId('acq-invoice-summary-count').innerHTML) + 1;
780 entryTbody = dojo.byId('acq-invoice-entry-tbody');
781 if(entryTemplate == null) {
782 entryTemplate = entryTbody.removeChild(dojo.byId('acq-invoice-entry-template'));
785 if(dojo.query('[lineitem=' + entry.lineitem() +']', entryTbody)[0])
786 // Is it ever valid to have multiple entries for 1 lineitem in a single invoice?
789 var row = entryTemplate.cloneNode(true);
790 row.setAttribute('lineitem', entry.lineitem());
791 row.setAttribute('entry_lineitem_row', entry.lineitem());
793 openils.acq.Lineitem.fetchAndRender(
794 entry.lineitem(), {},
797 entry.purchase_order(li.purchase_order());
798 nodeByName('title_details', row).innerHTML = html;
800 nodeByName('title_details', row).parentNode.id = 'li-title-ref-' + li.id();
801 console.log(dojo.byId('li-title-ref-' + li.id()));
803 updateReceiveLink(li);
805 // set some default values if otherwise unset
806 if (!invoicePane.getFieldValue('receiver')) {
807 invoicePane.setFieldValue('receiver', li.purchase_order().ordering_agency());
809 if (!invoicePane.getFieldValue('provider')) {
810 invoicePane.setFieldValue('provider', li.purchase_order().provider());
814 ['inv_item_count', 'phys_item_count', 'cost_billed', 'amount_paid'],
816 var dijitArgs = {required : true, constraints : {min: 0}, style : 'width:6em'};
817 if(field.match(/count/)) {
818 dijitArgs.style = 'width:4em;';
820 dijitArgs.style = 'width:9em;';
822 if(entry.isnew() && field == 'phys_item_count') {
823 // by default, attempt to pay for all non-canceled and as-of-yet-un-invoiced items
824 var count = Number(li.order_summary().item_count() || 0) -
825 Number(li.order_summary().cancel_count() || 0) -
826 Number(li.order_summary().invoice_count() || 0);
827 if(count < 0) count = 0;
828 dijitArgs.value = count;
833 new openils.widget.AutoFieldWidget({
837 dijitArgs : dijitArgs,
838 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
839 parentNode : nodeByName(field, row)
843 if(field == 'phys_item_count') {
844 dojo.connect(w, 'onChange',
846 // staff entered a higher number in the receive field than was originally ordered
847 // taking into account already invoiced items
848 var extra = Number(this.attr('value')) -
849 (Number(entry.lineitem().item_count()) - Number(entry.lineitem().order_summary().invoice_count()));
851 storeExtraCopies(entry, extra);
857 if(field == 'inv_item_count' || field == 'cost_billed') {
858 setPerCopyPrice(row, entry);
859 // update the per-copy count as invoice count and cost billed change
860 dojo.connect(w, 'onChange', function() { setPerCopyPrice(row, entry) } );
869 if (focusLineitem == li.id())
874 nodeByName('detach', row).onclick = function() {
875 var cost = widgetRegistry.acqie[entry.id()].cost_billed.getFormattedValue();
877 dojo.forEach(['isbn', 'upc', 'issn'],
879 var val = liMarcAttr(entry.lineitem(), ident);
880 if(val) idents.push(val);
884 var msg = dojo.string.substitute(
885 localeStrings.INVOICE_CONFIRM_ENTRY_DETACH, [
887 liMarcAttr(entry.lineitem(), 'title'),
888 liMarcAttr(entry.lineitem(), 'author'),
892 if(!confirm(msg)) return;
893 entryTbody.removeChild(row);
894 entry.isdeleted(true);
896 delete widgetRegistry.acqie[entry.id()];
900 entryTbody.appendChild(row);
903 function setPerCopyPrice(row, entry) {
904 var inv_w = widgetRegistry.acqie[entry.id()].inv_item_count;
905 var bill_w = widgetRegistry.acqie[entry.id()].cost_billed;
907 if (inv_w && bill_w) {
908 var invoiced = Number(inv_w.getFormattedValue());
909 var billed = Number(bill_w.getFormattedValue());
910 console.log(invoiced + ' : ' + billed);
912 nodeByName('amount_paid_per_copy', row).innerHTML = (billed / invoiced).toFixed(2);
914 nodeByName('amount_paid_per_copy', row).innerHTML = '0.00';
919 function liMarcAttr(lineitem, name) {
920 var attr = lineitem.attributes().filter(
923 attr.attr_type() == 'lineitem_marc_attr_definition' &&
924 attr.attr_name() == name)
928 return (attr) ? attr.attr_value() : '';
931 function saveChanges(args) {
933 createExtraCopies(function() { saveChangesPartTwo(args); });
936 // Define a helper function to 'unflesh' sub-objects from an fmclass object.
937 // 'this' specifies the object; the arguments specify a list of names of
941 dojo.forEach(arguments, function (n) {
943 if (_ !== null && typeof _ === 'object')
948 function saveChangesPartTwo(args) {
952 invoice.complete('f');
956 // Prepare an invoice for submission
958 invoice = new fieldmapper.acqinv();
961 invoice.ischanged(true); // for now, just always update
964 var e = invoicePane.mapValues(function (n, v) { invoice[n](v); });
965 if (e instanceof Error) {
971 invoice.complete('t');
974 // Prepare any charge items
975 var updateItems = [];
976 for(var id in widgetRegistry.acqii) {
977 var reg = widgetRegistry.acqii[id];
978 var item = reg._object;
979 if(item.ischanged() || item.isnew() || item.isdeleted()) {
980 updateItems.push(item);
981 if(item.isnew()) item.id(null);
982 for(var field in reg) {
983 if(field != '_object')
984 item[field]( reg[field].getFormattedValue() );
987 unflesh.call(item, 'purchase_order');
992 // Prepare any line items
993 var updateEntries = [];
994 for(var id in widgetRegistry.acqie) {
995 var reg = widgetRegistry.acqie[id];
996 var entry = reg._object;
997 if(entry.ischanged() || entry.isnew() || entry.isdeleted()) {
998 updateEntries.push(entry);
999 if(entry.isnew()) entry.id(null);
1001 for(var field in reg) {
1002 if(field != '_object')
1003 entry[field]( reg[field].getFormattedValue() );
1006 unflesh.call(entry, 'purchase_order', 'lineitem');
1011 progressDialog.show(true);
1012 fieldmapper.standardRequest(
1013 ['open-ils.acq', 'open-ils.acq.invoice.update'],
1015 params : [openils.User.authtoken, invoice, updateEntries, updateItems],
1016 oncomplete : function(r) {
1017 progressDialog.hide();
1018 var invoice = openils.Util.readResponse(r);
1021 return prorateInvoice(invoice);
1023 location.href = oilsBasePath + '/acq/invoice/view?create=1';
1025 location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
1033 function prorateInvoice(invoice) {
1034 if(!confirm(localeStrings.INVOICE_CONFIRM_PRORATE)) return;
1035 progressDialog.show(true);
1037 fieldmapper.standardRequest(
1038 ['open-ils.acq', 'open-ils.acq.invoice.apply_prorate'],
1040 params : [openils.User.authtoken, invoice.id()],
1041 oncomplete : function(r) {
1042 progressDialog.hide();
1043 var invoice = openils.Util.readResponse(r);
1045 location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
1052 function storeExtraCopies(entry, numExtra) {
1054 dojo.byId('acq-invoice-extra-copies-message').innerHTML =
1055 dojo.string.substitute(
1056 localeStrings.INVOICE_EXTRA_COPIES, [numExtra]);
1059 addCopyHandler = dojo.connect(
1063 extraCopies[entry.lineitem().id()] = {
1064 numExtra : numExtra,
1065 fund : extraCopiesFund.widget.attr('value')
1067 extraItemsDialog.hide();
1068 dojo.disconnect(addCopyHandler);
1076 widgetRegistry.acqie[entry.id()].phys_item_count.widget.attr('value', '');
1077 extraItemsDialog.hide()
1081 extraItemsDialog.show();
1084 function validateInvIdent(inv_ident, provider, receiver) {
1085 if (!(inv_ident && provider && receiver)) {
1086 console.info("not enough information to pre-validate inv_ident");
1090 openils.Util.show("ident-validation-spinner", "inline");
1091 var pcrud = new openils.PermaCrud();
1093 "acqinv", {"inv_ident": inv_ident, "provider": provider}, {
1094 "oncomplete": function(r) {
1095 openils.Util.hide("ident-validation-spinner");
1097 /* This could throw an event about the user not having perms,
1098 * but in such a case the whole interface is already busted
1100 r = openils.Util.readResponse(r);
1102 var w = invoicePane.getFieldWidget("inv_ident").widget;
1104 alert(localeStrings.INVOICE_IDENT_COLLIDE);
1105 w.validator = function() { return false; };
1108 w.validator = function() { return true; };
1118 function drawInvoicePane(parentNode, inv, args) {
1125 recv_date : {widgetValue : dojo.date.stamp.toISOString(new Date())},
1126 //receiver : {widgetValue : openils.User.user.ws_ou()},
1129 "onChange": function(val) {
1131 invoicePane && invoicePane.getFieldValue("inv_ident"),
1132 invoicePane && invoicePane.getFieldValue("provider"),
1138 recv_method : {widgetValue : 'PPR'}
1142 dojo.mixin(override, {
1145 store_options : { base_filter : { active :"t" } },
1146 onChange : function(val) {
1147 pane.setFieldValue('shipper', val);
1149 invoicePane && invoicePane.getFieldValue("inv_ident"),
1151 invoicePane && invoicePane.getFieldValue("receiver")
1156 shipper : { dijitArgs : { store_options : { base_filter : { active :"t" } } } }
1159 for(var field in args) {
1160 override[field] = {widgetValue : args[field]};
1163 // push the name of the invoice into the name display field after update
1164 override.inv_ident = dojo.mixin(
1166 {dijitArgs : {onChange :
1170 invoicePane && invoicePane.getFieldValue("provider"),
1171 invoicePane && invoicePane.getFieldValue("receiver")
1174 if (dojo.byId('acq-invoice-summary-name'))
1175 dojo.byId('acq-invoice-summary-name').innerHTML = newVal;
1181 pane = new openils.widget.EditPane({
1185 mode : (inv) ? 'edit' : 'create',
1186 hideActionButtons : true,
1187 overrideWidgetArgs : override,
1188 readOnly : (inv) && openils.Util.isTrue(inv.complete()),
1203 suppressFields : ['id', 'complete']
1207 parentNode.appendChild(pane.domNode);
1212 function createExtraCopies(oncomplete) {
1215 for(var liId in extraCopies) {
1216 var data = extraCopies[liId];
1217 for(var i = 0; i < data.numExtra; i++) {
1218 var lid = new fieldmapper.acqlid();
1221 lid.fund(data.fund);
1222 lid.recv_time('now');
1227 if(lids.length == 0)
1228 return oncomplete();
1230 fieldmapper.standardRequest(
1231 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1233 params : [openils.User.authtoken, lids, true],
1234 oncomplete : function(r) {
1235 if(openils.Util.readResponse(r))
1243 function smartSearchSubmitter() {
1244 performSearch(0, !dojo.byId('acq-unified-build-progressively').checked);
1248 openils.Util.addOnLoad(init);