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'];
23 var fundSearchFilter = {};
25 var cgi = new openils.CGI();
26 var pcrud = new openils.PermaCrud();
41 var widgetRegistry = {acqie : {}, acqii : {}};
43 var searchInitDone = false;
47 function nodeByName(name, context) {
48 return dojo.query('[name='+name+']', context)[0];
52 // before rendering any fund selectors, limit the funds to
53 // attempt to retrieve to those the user can actually use.
54 new openils.User().getPermOrgList(
55 ['ADMIN_INVOICE','CREATE_INVOICE','MANAGE_FUND'],
57 fundSearchFilter.org = orgs;
60 true, true // descendants, id_list
66 attachLi = cgi.param('attach_li') || [];
67 if (!dojo.isArray(attachLi))
68 attachLi = [attachLi];
70 attachPo = cgi.param('attach_po') || [];
71 if (!dojo.isArray(attachPo))
72 attachPo = [attachPo];
74 focusLineitem = new openils.CGI().param('focus_li');
76 totalInvoicedBox = dojo.byId('acq-total-invoiced-box');
77 totalPaidBox = dojo.byId('acq-total-paid-box');
78 balanceOwedBox = dojo.byId('acq-total-balance-box');
80 itemTypes = pcrud.retrieveAll('aiit');
82 dojo.byId('acq-invoice-summary-toggle-off').onclick = function() {
83 openils.Util.hide(dojo.byId('acq-invoice-summary'));
84 openils.Util.show(dojo.byId('acq-invoice-summary-small'));
87 dojo.byId('acq-invoice-summary-toggle-on').onclick = function() {
88 openils.Util.show(dojo.byId('acq-invoice-summary'));
89 openils.Util.hide(dojo.byId('acq-invoice-summary-small'));
92 if(cgi.param('create')) {
95 // show summary info by default for new invoices
96 dojo.byId('acq-invoice-summary-toggle-on').onclick();
99 dojo.byId('acq-invoice-summary-toggle-off').onclick();
100 fieldmapper.standardRequest(
101 ['open-ils.acq', 'open-ils.acq.invoice.retrieve.authoritative'],
103 params : [openils.User.authtoken, invoiceId],
104 oncomplete : function(r) {
105 invoice = openils.Util.readResponse(r);
112 extraCopiesFund = new openils.widget.AutoFieldWidget({
115 searchFilter : {active : 't'},
116 labelFormat : fundLabelFormat,
117 searchFormat : fundSearchFormat,
118 searchFilter : fundSearchFilter,
119 dijitArgs : {required : true},
120 parentNode : dojo.byId('acq-invoice-extra-copies-fund')
122 extraCopiesFund.build();
125 function renderInvoice() {
127 // in create mode, let the LI or PO render the invoice with seed data
128 if( !(cgi.param('create') && (attachPo.length || attachLi.length)) ) {
129 invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), invoice);
132 dojo.byId('acq-invoice-new-item').onclick = function() {
133 var item = new fieldmapper.acqii();
134 item.id(virtualId--);
136 addInvoiceItem(item);
141 if(invoice && openils.Util.isTrue(invoice.complete())) {
143 dojo.forEach( // hide widgets that should not be visible for a completed invoice
144 dojo.query('.hide-complete'),
145 function(node) { openils.Util.hide(node); }
148 new openils.User().getPermOrgList(
149 'ACQ_INVOICE_REOPEN',
151 if(orgs.indexOf(invoice.receiver()) >= 0)
152 openils.Util.show('acq-invoice-reopen-button-wrapper', 'inline');
159 // display items and entries in ID order
160 // which effectively equates to add order.
161 function idsort(a, b) { return a.id() < b.id() ? -1 : 1 }
165 invoice.items().sort(idsort),
167 addInvoiceItem(item);
172 invoice.entries().sort(idsort),
174 addInvoiceEntry(entry);
179 if(attachLi.length) doAttachLi();
180 if(attachPo.length) doAttachPo(0);
183 function doAttachLi(skipInit) {
185 //var invoiceArgs = {provider : lineitem.provider(), shipper : lineitem.provider()};
186 if(cgi.param('create') && !skipInit) {
188 // use the first LI in the list to determine the default provider
189 fieldmapper.standardRequest(
190 ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
192 params : [openils.User.authtoken, attachLi[0], {clear_marc:1}],
193 oncomplete : function(r) {
194 var li = openils.Util.readResponse(r);
195 invoicePane = drawInvoicePane(
196 dojo.byId('acq-view-invoice-div'), null,
197 {provider : li.provider(), shipper : li.provider()}
204 dojo.forEach(attachLi,
206 var entry = new fieldmapper.acqie();
207 entry.id(virtualId--);
210 addInvoiceEntry(entry);
215 function doAttachPo(idx) {
217 if (idx == attachPo.length) return;
218 var poId = attachPo[idx];
220 fieldmapper.standardRequest(
221 ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
224 openils.User.authtoken, poId,
225 {flesh_lineitem_ids : true, flesh_po_items : true}
227 oncomplete: function(r) {
228 var po = openils.Util.readResponse(r);
230 if(cgi.param('create') && idx == 0) {
231 // render the invoice using some seed data from the first PO
232 var invoiceArgs = {provider : po.provider(), shipper : po.provider()};
233 invoicePane = drawInvoicePane(dojo.byId('acq-view-invoice-div'), null, invoiceArgs);
236 dojo.forEach(po.lineitems(),
238 var entry = new fieldmapper.acqie();
239 entry.id(virtualId--);
241 entry.lineitem(lineitem);
242 entry.purchase_order(po);
243 addInvoiceEntry(entry);
247 dojo.forEach(po.po_items(),
249 var item = new fieldmapper.acqii();
250 item.id(virtualId--);
252 item.fund(poItem.fund());
253 item.title(poItem.title());
254 item.author(poItem.author());
255 item.note(poItem.note());
256 item.inv_item_type(poItem.inv_item_type());
257 item.purchase_order(po);
258 item.po_item(poItem);
259 addInvoiceItem(item);
270 var cookieUriSSL, cookieSvc, cookieMgr;
272 function performSearch(pageDir, clearFirst) {
274 clearSearchResTable();
276 var searchObject = termManager.buildSearchObject();
278 if (openils.XUL.isXUL()) {
280 cookieSvc.setCookieString(cookieUriSSL, null,
281 "invs=" + base64Encode(searchObject) + ';max-age=2592000', null);
283 cookieSvc.setCookieString(cookieUriSSL, null,
284 "invc=" + dojo.byId("acq-unified-conjunction").getValue() +
285 ';max-age=2592000', null);
289 dojo.cookie('invs', base64Encode(searchObject));
290 dojo.cookie('invc', dojo.byId("acq-unified-conjunction").getValue());
293 if (pageDir == 0) { // new search
294 resultsLoader.displayOffset = 0;
296 resultsLoader.displayOffset += pageDir * resultsLoader.displayLimit;
299 if (resultsLoader.displayOffset == 0) {
300 openils.Util.hide('acq-inv-search-prev');
302 openils.Util.show('acq-inv-search-prev', 'inline');
305 if (dojo.byId('acq-invoice-search-limit-invoiceable').checked) {
306 if (!searchObject.jub)
307 searchObject.jub = [];
309 // exclude lineitems that are "cancelled" (sidebar: 'Mericans spell it 'canceled')
310 searchObject.jub.push({state : 'cancelled', '__not' : true});
312 // exclude lineitems already linked to this invoice
313 if (invoice && invoice.id() > 0) {
314 if (!searchObject.acqinv)
315 searchObject.acqinv = [];
316 searchObject.acqinv.push({id : invoice.id(), '__not' : true});
319 // limit to lineitems that have invoiceable copies
320 searchObject.acqlisumi = [{item_count : 1, '_gte' : true}];
322 // limit to provider if a provider is selected
323 var provider = invoicePane.getFieldValue('provider');
325 if (!searchObject.jub.filter(function(i) { return i.provider != null }).length)
326 searchObject.jub.push({provider : provider});
330 if (dojo.byId('acq-invoice-search-sort-title').checked) {
331 uriManager.order_by =
332 [ {"class": "acqlia", "field":"attr_value", "transform":"first"} ];
335 resultsLoader.lastSearch = searchObject;
336 resultManager.go(searchObject)
337 console.log('Lineitem Search: ' + js2JSON(searchObject));
338 focusLastSearchInput();
342 function renderUnifiedSearch() {
344 if (!searchInitDone) {
346 searchInitDone = true;
347 termManager = new TermManager();
348 resultManager = new ResultManager();
349 resultsLoader = new searchResultsLoader();
350 uriManager = new URIManager();
352 // define custom lineitem result handler
353 resultManager.result_types = {
355 "search_options": { "id_list": true },
356 "revealer": function() { },
357 "finisher": function() {
358 resultsLoader.batch_length = resultManager.count_results;
360 "adder": function(li) {
361 resultsLoader.addLineitem(li);
363 "interface": resultsLoader
366 "revealer": function() { }
371 resultManager.no_results_popup = true;
372 resultManager.submitter = smartSearchSubmitter;
374 var searchObject, searchConjunction;
376 if (openils.XUL.isXUL()) {
380 var ios = Components.classes["@mozilla.org/network/io-service;1"]
381 .getService(Components.interfaces.nsIIOService);
383 cookieUriSSL = ios.newURI("https://" + location.hostname, null, null);
385 cookieSvc = Components.classes["@mozilla.org/cookieService;1"]
386 .getService(Components.interfaces.nsICookieService);
389 cookieManager = Components.classes["@mozilla.org/cookiemanager;1"]
390 .getService(Components.interfaces.nsICookieManager);
393 var iter = cookieManager.enumerator;
394 while (iter.hasMoreElements()) {
395 var cookie = iter.getNext();
396 if (cookie instanceof Components.interfaces.nsICookie) {
397 if (cookie.name == 'invs')
398 searchObject = cookie.value;
399 if (cookie.name == 'invc')
400 searchConjunction = cookie.value;
405 // useful for web-based testing
406 searchObject = dojo.cookie('invs');
407 searchConjunction = dojo.cookie('invc');
412 // if there is a search object cookie, populate the search form
413 termManager.reflect(base64Decode(searchObject));
414 dojo.byId("acq-unified-conjunction").setValue(searchConjunction);
417 console.log('adding row');
418 termManager.addRow();
422 dojo.addClass(dojo.byId('oils-acq-invoice-table'), 'hidden');
423 dojo.removeClass(dojo.byId('oils-acq-invoice-search'), 'hidden');
424 focusLastSearchInput();
427 function focusLastSearchInput() {
428 // TODO: see about making this better and moving it into search/unified.js
429 var wnodes = dojo.query('[name=widget]');
430 var inputNode = wnodes.item(wnodes.length - 1).firstChild;
440 var resultsTbody, resultsRow;
441 function searchResultsLoader() {
442 this.displayOffset = 0;
443 this.displayLimit = 10;
446 resultsTbody = dojo.byId('acq-invoice-search-results-tbody');
447 resultsRow = resultsTbody.removeChild(dojo.byId('acq-invoice-search-results-tr'));
450 this.addLineitem = function(li_id) {
451 console.log('Adding search result lineitem ' + li_id);
452 var row = resultsRow.cloneNode(true);
453 resultsTbody.appendChild(row);
454 var checkbox = dojo.query('[name=search-results-checkbox]', row)[0];
455 checkbox.setAttribute('lineitem', li_id);
457 // this lineitem is already part of the invoice
458 if (dojo.query('[entry_lineitem_row=' + li_id + ']')[0]) {
459 checkbox.disabled = true;
460 dojo.addClass(checkbox.parentNode, 'search-results-already-invoiced');
463 openils.acq.Lineitem.fetchAndRender(
466 dojo.query('[name=search-results-content-div]', row)[0].innerHTML = html;
472 function addSelectedToInvoice() {
473 var inputs = dojo.query('[name=search-results-checkbox]');
477 if (checkbox.checked) {
478 attachLi.push(checkbox.getAttribute('lineitem'));
479 checkbox.disabled = true;
480 checkbox.checked = false;
481 dojo.addClass(checkbox.parentNode, 'search-results-already-invoiced');
488 allResSelected = false;
489 function clearSearchResTable() {
490 allResSelected = false;
491 while (resultsTbody.childNodes[0])
492 resultsTbody.removeChild(resultsTbody.childNodes[0]);
495 function selectSearchResults() {
496 allResSelected = !allResSelected;
497 dojo.query('[name=search-results-checkbox]').forEach(
498 function(input) { input.checked = allResSelected });
501 function updateTotalCost() {
504 for(var id in widgetRegistry.acqii)
505 if(!widgetRegistry.acqii[id]._object.isdeleted())
506 totalCost += Number(widgetRegistry.acqii[id].cost_billed.getFormattedValue());
507 for(var id in widgetRegistry.acqie)
508 if(!widgetRegistry.acqie[id]._object.isdeleted())
509 totalCost += Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue());
510 totalInvoicedBox.innerHTML = totalCost.toFixed(2);
513 for(var id in widgetRegistry.acqii)
514 if(!widgetRegistry.acqii[id]._object.isdeleted())
515 totalPaid += Number(widgetRegistry.acqii[id].amount_paid.getFormattedValue());
516 for(var id in widgetRegistry.acqie)
517 if(!widgetRegistry.acqie[id]._object.isdeleted())
518 totalPaid += Number(widgetRegistry.acqie[id].amount_paid.getFormattedValue());
519 totalPaidBox.innerHTML = totalPaid.toFixed(2);
521 var buttonsDisabled = false;
523 if(totalPaid > totalCost || totalPaid < 0) {
524 openils.Util.addCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
525 invoiceSaveButton.attr('disabled', true);
526 invoiceProrateButton.attr('disabled', true);
527 buttonsDisabled = true;
529 openils.Util.removeCSSClass(totalPaidBox, 'acq-invoice-invalid-amount');
530 invoiceSaveButton.attr('disabled', false);
531 invoiceProrateButton.attr('disabled', false);
535 openils.Util.addCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
536 invoiceSaveButton.attr('disabled', true);
537 invoiceProrateButton.attr('disabled', true);
539 openils.Util.removeCSSClass(totalInvoicedBox, 'acq-invoice-invalid-amount');
540 if(!buttonsDisabled) {
541 invoiceSaveButton.attr('disabled', false);
542 invoiceProrateButton.attr('disabled', false);
546 if(totalPaid == totalCost) { // XXX: too rigid?
547 invoiceCloseButton.attr('disabled', false);
549 invoiceCloseButton.attr('disabled', true);
552 balanceOwedBox.innerHTML = (totalCost - totalPaid).toFixed(2);
554 updateExpectedCost();
558 function registerWidget(obj, field, widget, callback) {
559 var blob = widgetRegistry[obj.classname];
561 blob[obj.id()] = {_object : obj};
562 blob[obj.id()][field] = widget;
565 dojo.connect(w, 'onChange',
571 if(callback) callback(w, ww);
577 function addInvoiceItem(item) {
578 itemTbody = dojo.byId('acq-invoice-item-tbody');
579 if(itemTemplate == null) {
580 itemTemplate = itemTbody.removeChild(dojo.byId('acq-invoice-item-template'));
583 var row = itemTemplate.cloneNode(true);
584 var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
587 ['title', 'author', 'cost_billed', 'amount_paid'],
591 if(field == 'title' || field == 'author') {
592 //args = {style : 'width:10em'};
593 } else if(field == 'cost_billed' || field == 'amount_paid') {
594 args = {required : true, style : 'width: 8em'};
600 new openils.widget.AutoFieldWidget({
604 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
606 parentNode : nodeByName(field, row)
609 if (field == "cost_billed") {
611 w, "onChange", function(value) {
612 var paid = widgetRegistry.acqii[item.id()].amount_paid.widget;
613 if (value && isNaN(paid.attr("value")))
614 paid.attr("value", value);
624 /* ----------- fund -------------- */
629 labelFormat : fundLabelFormat,
630 searchFormat : fundSearchFormat,
631 searchFilter : fundSearchFilter,
632 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
633 dijitArgs : {required : true},
634 parentNode : nodeByName('fund', row)
637 if(item.fund_debit()) {
638 fundArgs.searchFilter = {'-or' : [{active : 't'}, {id : item.fund()}]};
640 fundArgs.searchFilter = {active : 't'}
641 if(itemType && openils.Util.isTrue(itemType.prorate()))
642 fundArgs.dijitArgs = {disabled : true};
645 var fundWidget = new openils.widget.AutoFieldWidget(fundArgs);
646 registerWidget(item, 'fund', fundWidget);
648 /* ---------- inv_item_type ------------- */
652 // read-only item view for items that were the result of a po-item
653 var po = item.purchase_order();
654 var po_item = item.po_item();
655 var node = nodeByName('inv_item_type', row);
656 var itemType = itemTypes.filter(function(t) { return (t.code() == item.inv_item_type()) })[0];
657 orderDate = (!po.order_date()) ? '' :
658 dojo.date.locale.format(dojo.date.stamp.fromISOString(po.order_date()), {selector:'date'});
660 node.innerHTML = dojo.string.substitute(
661 localeStrings.INVOICE_ITEM_PO_DETAILS,
668 po_item.estimated_cost()
677 new openils.widget.AutoFieldWidget({
679 fmField : 'inv_item_type',
680 parentNode : nodeByName('inv_item_type', row),
681 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
682 dijitArgs : {required : true}
685 // When the inv_item_type is set to prorate=true, don't allow the user the edit the fund
686 // since this charge will be prorated against (potentially) multiple funds
687 dojo.connect(w, 'onChange',
689 if(!item.fund_debit()) {
690 var itemType = itemTypes.filter(function(t) { return (t.code() == w.attr('value')) })[0];
691 if(!itemType) return;
692 if(openils.Util.isTrue(itemType.prorate())) {
693 fundWidget.widget.attr('disabled', true);
694 fundWidget.widget.attr('value', '');
696 fundWidget.widget.attr('disabled', false);
705 nodeByName('delete', row).onclick = function() {
706 var cost = widgetRegistry.acqii[item.id()].cost_billed.getFormattedValue();
707 var msg = dojo.string.substitute(
708 localeStrings.INVOICE_CONFIRM_ITEM_DELETE, [
710 widgetRegistry.acqii[item.id()].inv_item_type.getFormattedValue() || ''
713 if(!confirm(msg)) return;
714 itemTbody.removeChild(row);
715 item.isdeleted(true);
717 delete widgetRegistry.acqii[item.id()];
721 itemTbody.appendChild(row);
725 function updateReceiveLink(li) {
727 return; /* can't do this with unsaved invoices */
729 var link = dojo.byId("acq-view-invoice-receive-link");
730 if (link.onclick) return; /* only need to do this once */
732 /* don't do this if there's nothing receivable on the lineitem */
733 if (li.order_summary().recv_count() + li.order_summary().cancel_count() >=
734 li.order_summary().item_count())
737 openils.Util.show("acq-view-invoice-receive");
738 link.onclick = function() { location.href = oilsBasePath + '/acq/invoice/receive/' + invoiceId; };
742 * Ensures focusLineitem is in view and causes a brief
743 * border around the lineitem to come to life then fade.
746 if (!focusLineitem) return;
748 // set during addLineitem()
749 var node = dojo.byId('li-title-ref-' + focusLineitem);
751 console.log('focus: li-title-ref-' + focusLineitem + ' : ' + node);
753 // LI may not yet be rendered
756 console.log('focusing ' + focusLineitem);
758 // prevent numerous re-focuses
759 focusLineitem = null;
761 // causes the full row to be visible
762 dijit.scrollIntoView(node);
764 dojo.require('dojox.fx');
768 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
774 // expected cost is totalCostInvoiced + totalCostNotYetInvoiced
775 function updateExpectedCost() {
777 var cost = Number(totalInvoicedBox.innerHTML || 0);
779 // for any LI's that are not yet billed (i.e. filled in)
780 // use the total expected cost for that lineitem.
781 for(var id in widgetRegistry.acqie) {
782 var entry = widgetRegistry.acqie[id]._object;
783 if(!entry.isdeleted()) {
784 if (Number(widgetRegistry.acqie[id].cost_billed.getFormattedValue()) == 0) {
785 var li = entry.lineitem();
787 Number(li.order_summary().estimated_amount()) -
788 Number(li.order_summary().paid_amount());
793 dojo.byId('acq-invoice-summary-cost').innerHTML = cost.toFixed(2);
796 var invoicEntryWidgets = {};
797 function addInvoiceEntry(entry) {
798 console.log('Adding new entry for lineitem ' + entry.lineitem());
800 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-header'), 'hidden');
801 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-thead'), 'hidden');
802 openils.Util.removeCSSClass(dojo.byId('acq-invoice-entry-tbody'), 'hidden');
804 dojo.byId('acq-invoice-summary-count').innerHTML =
805 Number(dojo.byId('acq-invoice-summary-count').innerHTML) + 1;
807 entryTbody = dojo.byId('acq-invoice-entry-tbody');
808 if(entryTemplate == null) {
809 entryTemplate = entryTbody.removeChild(dojo.byId('acq-invoice-entry-template'));
812 if(dojo.query('[lineitem=' + entry.lineitem() +']', entryTbody)[0])
813 // Is it ever valid to have multiple entries for 1 lineitem in a single invoice?
816 var row = entryTemplate.cloneNode(true);
817 row.setAttribute('lineitem', entry.lineitem());
818 row.setAttribute('entry_lineitem_row', entry.lineitem());
820 openils.acq.Lineitem.fetchAndRender(
821 entry.lineitem(), {},
824 entry.purchase_order(li.purchase_order());
825 nodeByName('title_details', row).innerHTML = html;
827 nodeByName('title_details', row).parentNode.id = 'li-title-ref-' + li.id();
828 console.log(dojo.byId('li-title-ref-' + li.id()));
830 updateReceiveLink(li);
832 // set some default values if otherwise unset
833 if (!invoicePane.getFieldValue('receiver')) {
834 invoicePane.setFieldValue('receiver', li.purchase_order().ordering_agency());
836 if (!invoicePane.getFieldValue('provider')) {
837 invoicePane.setFieldValue('provider', li.purchase_order().provider());
841 ['inv_item_count', 'phys_item_count', 'cost_billed', 'amount_paid'],
843 var dijitArgs = {required : true, constraints : {min: 0}, style : 'width:6em'};
844 if(field.match(/count/)) {
845 dijitArgs.style = 'width:4em;';
847 dijitArgs.style = 'width:9em;';
849 if (entry.isnew() && (field == 'phys_item_count' || field == 'inv_item_count')) {
850 // by default, attempt to pay for all non-canceled and as-of-yet-un-invoiced items
851 var count = Number(li.order_summary().item_count() || 0) -
852 Number(li.order_summary().cancel_count() || 0) -
853 Number(li.order_summary().invoice_count() || 0);
854 if(count < 0) count = 0;
855 dijitArgs.value = count;
860 new openils.widget.AutoFieldWidget({
864 dijitArgs : dijitArgs,
865 readOnly : invoice && openils.Util.isTrue(invoice.complete()),
866 parentNode : nodeByName(field, row)
870 if(field == 'phys_item_count') {
871 dojo.connect(w, 'onChange',
873 // staff entered a higher number in the receive field than was originally ordered
874 // taking into account already invoiced items
875 var extra = Number(this.attr('value')) -
876 (Number(entry.lineitem().item_count()) - Number(entry.lineitem().order_summary().invoice_count()));
878 storeExtraCopies(entry, extra);
884 if (field == "cost_billed") {
885 // hooks applied with dojo.connect to dijit events are additive, so there's no conflict between this and what comes next
887 w, "onChange", function(value) {
888 var paid = widgetRegistry.acqie[entry.id()].amount_paid.widget;
889 if (value && isNaN(paid.attr("value")))
890 paid.attr("value", value);
894 if(field == 'inv_item_count' || field == 'cost_billed') {
895 setPerCopyPrice(row, entry);
896 // update the per-copy count as invoice count and cost billed change
897 dojo.connect(w, 'onChange', function() { setPerCopyPrice(row, entry) } );
906 if (focusLineitem == li.id())
911 nodeByName('detach', row).onclick = function() {
912 var cost = widgetRegistry.acqie[entry.id()].cost_billed.getFormattedValue();
914 dojo.forEach(['isbn', 'upc', 'issn'],
916 var val = liMarcAttr(entry.lineitem(), ident);
917 if(val) idents.push(val);
921 var msg = dojo.string.substitute(
922 localeStrings.INVOICE_CONFIRM_ENTRY_DETACH, [
924 liMarcAttr(entry.lineitem(), 'title'),
925 liMarcAttr(entry.lineitem(), 'author'),
929 if(!confirm(msg)) return;
930 entryTbody.removeChild(row);
931 entry.isdeleted(true);
933 delete widgetRegistry.acqie[entry.id()];
937 entryTbody.appendChild(row);
940 function setPerCopyPrice(row, entry) {
941 var inv_w = widgetRegistry.acqie[entry.id()].inv_item_count;
942 var bill_w = widgetRegistry.acqie[entry.id()].cost_billed;
944 if (inv_w && bill_w) {
945 var invoiced = Number(inv_w.getFormattedValue());
946 var billed = Number(bill_w.getFormattedValue());
947 console.log(invoiced + ' : ' + billed);
949 nodeByName('amount_paid_per_copy', row).innerHTML = (billed / invoiced).toFixed(2);
951 nodeByName('amount_paid_per_copy', row).innerHTML = '0.00';
956 function liMarcAttr(lineitem, name) {
957 var attr = lineitem.attributes().filter(
960 attr.attr_type() == 'lineitem_marc_attr_definition' &&
961 attr.attr_name() == name)
965 return (attr) ? attr.attr_value() : '';
968 function saveChanges(args) {
970 createExtraCopies(function() { saveChangesPartTwo(args); });
973 // Define a helper function to 'unflesh' sub-objects from an fmclass object.
974 // 'this' specifies the object; the arguments specify a list of names of
978 dojo.forEach(arguments, function (n) {
980 if (_ !== null && typeof _ === 'object')
985 function saveChangesPartTwo(args) {
989 invoice.complete('f');
993 // Prepare an invoice for submission
995 invoice = new fieldmapper.acqinv();
998 invoice.ischanged(true); // for now, just always update
1001 var e = invoicePane.mapValues(function (n, v) { invoice[n](v); });
1002 if (e instanceof Error) {
1008 invoice.complete('t');
1011 // Prepare any charge items
1012 var updateItems = [];
1013 for(var id in widgetRegistry.acqii) {
1014 var reg = widgetRegistry.acqii[id];
1015 var item = reg._object;
1016 if(item.ischanged() || item.isnew() || item.isdeleted()) {
1017 updateItems.push(item);
1018 if(item.isnew()) item.id(null);
1019 for(var field in reg) {
1020 if(field != '_object')
1021 item[field]( reg[field].getFormattedValue() );
1024 unflesh.call(item, 'purchase_order');
1029 // Prepare any line items
1030 var updateEntries = [];
1031 for(var id in widgetRegistry.acqie) {
1032 var reg = widgetRegistry.acqie[id];
1033 var entry = reg._object;
1034 if(entry.ischanged() || entry.isnew() || entry.isdeleted()) {
1035 updateEntries.push(entry);
1036 if(entry.isnew()) entry.id(null);
1038 for(var field in reg) {
1039 if(field != '_object')
1040 entry[field]( reg[field].getFormattedValue() );
1043 unflesh.call(entry, 'purchase_order', 'lineitem');
1048 progressDialog.show(true);
1049 fieldmapper.standardRequest(
1050 ['open-ils.acq', 'open-ils.acq.invoice.update'],
1052 params : [openils.User.authtoken, invoice, updateEntries, updateItems],
1053 oncomplete : function(r) {
1054 progressDialog.hide();
1055 var invoice = openils.Util.readResponse(r);
1058 return prorateInvoice(invoice);
1060 location.href = oilsBasePath + '/acq/invoice/view?create=1';
1062 location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
1070 function prorateInvoice(invoice) {
1071 if(!confirm(localeStrings.INVOICE_CONFIRM_PRORATE)) return;
1072 progressDialog.show(true);
1074 fieldmapper.standardRequest(
1075 ['open-ils.acq', 'open-ils.acq.invoice.apply_prorate'],
1077 params : [openils.User.authtoken, invoice.id()],
1078 oncomplete : function(r) {
1079 progressDialog.hide();
1080 var invoice = openils.Util.readResponse(r);
1082 location.href = oilsBasePath + '/acq/invoice/view/' + invoice.id();
1089 function storeExtraCopies(entry, numExtra) {
1091 dojo.byId('acq-invoice-extra-copies-message').innerHTML =
1092 dojo.string.substitute(
1093 localeStrings.INVOICE_EXTRA_COPIES, [numExtra]);
1096 addCopyHandler = dojo.connect(
1100 extraCopies[entry.lineitem().id()] = {
1101 numExtra : numExtra,
1102 fund : extraCopiesFund.widget.attr('value')
1104 extraItemsDialog.hide();
1105 dojo.disconnect(addCopyHandler);
1113 widgetRegistry.acqie[entry.id()].phys_item_count.widget.attr('value', '');
1114 extraItemsDialog.hide()
1118 extraItemsDialog.show();
1121 function validateInvIdent(inv_ident, provider, receiver) {
1122 if (!(inv_ident && provider && receiver)) {
1123 console.info("not enough information to pre-validate inv_ident");
1127 openils.Util.show("ident-validation-spinner", "inline");
1128 var pcrud = new openils.PermaCrud();
1130 "acqinv", {"inv_ident": inv_ident, "provider": provider}, {
1131 "oncomplete": function(r) {
1132 openils.Util.hide("ident-validation-spinner");
1134 /* This could throw an event about the user not having perms,
1135 * but in such a case the whole interface is already busted
1137 r = openils.Util.readResponse(r);
1139 var w = invoicePane.getFieldWidget("inv_ident").widget;
1141 alert(localeStrings.INVOICE_IDENT_COLLIDE);
1142 w.validator = function() { return false; };
1145 w.validator = function() { return true; };
1155 function drawInvoicePane(parentNode, inv, args) {
1162 recv_date : {widgetValue : dojo.date.stamp.toISOString(new Date())},
1163 //receiver : {widgetValue : openils.User.user.ws_ou()},
1166 "onChange": function(val) {
1168 invoicePane && invoicePane.getFieldValue("inv_ident"),
1169 invoicePane && invoicePane.getFieldValue("provider"),
1175 recv_method : {widgetValue : 'PPR'}
1179 dojo.mixin(override, {
1182 store_options : { base_filter : { active :"t" } },
1183 onChange : function(val) {
1184 pane.setFieldValue('shipper', val);
1186 invoicePane && invoicePane.getFieldValue("inv_ident"),
1188 invoicePane && invoicePane.getFieldValue("receiver")
1193 shipper : { dijitArgs : { store_options : { base_filter : { active :"t" } } } }
1196 for(var field in args) {
1197 override[field] = {widgetValue : args[field]};
1200 // push the name of the invoice into the name display field after update
1201 override.inv_ident = dojo.mixin(
1203 {dijitArgs : {onChange :
1207 invoicePane && invoicePane.getFieldValue("provider"),
1208 invoicePane && invoicePane.getFieldValue("receiver")
1211 if (dojo.byId('acq-invoice-summary-name'))
1212 dojo.byId('acq-invoice-summary-name').innerHTML = newVal;
1218 pane = new openils.widget.EditPane({
1222 mode : (inv) ? 'edit' : 'create',
1223 hideActionButtons : true,
1224 overrideWidgetArgs : override,
1225 readOnly : (inv) && openils.Util.isTrue(inv.complete()),
1240 suppressFields : ['id', 'complete']
1244 parentNode.appendChild(pane.domNode);
1249 function createExtraCopies(oncomplete) {
1252 for(var liId in extraCopies) {
1253 var data = extraCopies[liId];
1254 for(var i = 0; i < data.numExtra; i++) {
1255 var lid = new fieldmapper.acqlid();
1258 lid.fund(data.fund);
1259 lid.recv_time('now');
1264 if(lids.length == 0)
1265 return oncomplete();
1267 fieldmapper.standardRequest(
1268 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1270 params : [openils.User.authtoken, lids, true],
1271 oncomplete : function(r) {
1272 if(openils.Util.readResponse(r))
1280 function smartSearchSubmitter() {
1281 performSearch(0, !dojo.byId('acq-unified-build-progressively').checked);
1285 openils.Util.addOnLoad(init);