diff --git a/Chapter04/favicon.ico b/Chapter04/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter04/favicon.ico and /dev/null differ diff --git a/Chapter05/Documentation/answers/composer/hlcAdmin_complete.js b/Chapter05/Documentation/answers/composer/hlcAdmin_complete.js index 8e9e8b9..46b188c 100644 --- a/Chapter05/Documentation/answers/composer/hlcAdmin_complete.js +++ b/Chapter05/Documentation/answers/composer/hlcAdmin_complete.js @@ -24,8 +24,7 @@ const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefi const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; -// const svc = require('./Z2B_Services'); -// const mod = 'hlcAdmin.js'; + /** * display the admin and network info diff --git a/Chapter05/Documentation/answers/js/z2b-admin_complete.js b/Chapter05/Documentation/answers/js/z2b-admin_complete.js index 67f421a..f3c3ffc 100644 --- a/Chapter05/Documentation/answers/js/z2b-admin_complete.js +++ b/Chapter05/Documentation/answers/js/z2b-admin_complete.js @@ -18,7 +18,6 @@ let creds; let connection; -let msgPort = null; let _blctr = 0; /** @@ -34,19 +33,6 @@ function loadAdminUX () listMemRegistries(); }); } -/** - * connect to the provided web socket - * @param {String} _target - location to post messages - * @param {Integer} _port - web socket port # - */ -function wsDisplay(_target, _port) -{ - let content = $('#'+_target); - let wsSocket = new WebSocket('ws://localhost:'+_port); - wsSocket.onopen = function () {wsSocket.send('connected to client');}; - wsSocket.onmessage = function (message) {content.append(formatMessage(message.data));}; - wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ' + error);}; -} /** * list the available business networks */ @@ -361,7 +347,7 @@ function preLoad() $('#body').empty(); let options = {}; $.when($.post('/setup/autoLoad', options)).done(function (_results) - { msgPort = _results.port; wsDisplay('body', msgPort); }); + { console.log('Autoload Initiated'); $('#body').append('

Autoload Initiated

'); }); } /** @@ -754,28 +740,9 @@ function getHistorian() */ function getChainEvents() { - $.when($.get('fabric/getChainEvents')).done(function(_res) - { let _str = '

Get Chain events requested. Sending to port: '+_res.port+'

'; - let content = $('#blockchain'); - let csSocket = new WebSocket('ws://localhost:'+_res.port); - csSocket.onopen = function () {csSocket.send('connected to client');}; - csSocket.onmessage = function (message) { - _blctr ++; - if (message.data !== 'connected') - {$(content).append('block '+JSON.parse(message.data).header.number+'
Hash: '+JSON.parse(message.data).header.data_hash+'
'); - if (_blctr > 4) {let leftPos = $(content).scrollLeft(); $(content).animate({scrollLeft: leftPos + 300}, 250);} - } - }; - csSocket.onerror = function (error) {console.log('WebSocket error: ' + error);}; - $('#admin-forms').empty(); - $('#admin-forms').append(_str); + $.when($.get('/fabric/getChainEvents')).done(function(_res) + { $('#body').append('

Get Chain events requested.

'); + let _host = (host_address.slice(0,9) === 'localhost') ? 'localhost' : host_address; + console.log('getChainEvents host_address: '+_host); }); -} -/** - * display blockchain updates - */ -function displayAdminUpdate() -{ - let toLoad = 'adminHelp.html'; - $.when($.get(toLoad)).done(function(_page){$('#admin-forms').empty(); $('#admin-forms').append(_page);}); } \ No newline at end of file diff --git a/Chapter05/HTML/favicon.ico b/Chapter05/HTML/favicon.ico old mode 100755 new mode 100644 index fc9e25d..3dbe425 Binary files a/Chapter05/HTML/favicon.ico and b/Chapter05/HTML/favicon.ico differ diff --git a/Chapter05/HTML/js/z2b-admin.js b/Chapter05/HTML/js/z2b-admin.js index 1ad3017..3186b1e 100644 --- a/Chapter05/HTML/js/z2b-admin.js +++ b/Chapter05/HTML/js/z2b-admin.js @@ -18,7 +18,6 @@ let creds; let connection; -let msgPort = null; let _blctr = 0; /** @@ -34,19 +33,6 @@ function loadAdminUX () listMemRegistries(); }); } -/** - * connect to the provided web socket - * @param {String} _target - location to post messages - * @param {Integer} _port - web socket port # - */ -function wsDisplay(_target, _port) -{ - let content = $('#'+_target); - let wsSocket = new WebSocket('ws://localhost:'+_port); - wsSocket.onopen = function () {wsSocket.send('connected to client');}; - wsSocket.onmessage = function (message) {content.append(formatMessage(message.data));}; - wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ' + error);}; -} /** * list the available business networks */ @@ -339,7 +325,7 @@ function preLoad() $('#body').empty(); let options = {}; $.when($.post('/setup/autoLoad', options)).done(function (_results) - { msgPort = _results.port; wsDisplay('body', msgPort); }); + { console.log('Autoload Initiated'); $('#body').append('

Autoload Initiated

'); }); } /** @@ -732,21 +718,10 @@ function getHistorian() */ function getChainEvents() { - $.when($.get('fabric/getChainEvents')).done(function(_res) - { let _str = '

Get Chain events requested. Sending to port: '+_res.port+'

'; - let content = $('#blockchain'); - let csSocket = new WebSocket('ws://localhost:'+_res.port); - csSocket.onopen = function () {csSocket.send('connected to client');}; - csSocket.onmessage = function (message) { - _blctr ++; - if (message.data !== 'connected') - {$(content).append('block '+JSON.parse(message.data).header.number+'
Hash: '+JSON.parse(message.data).header.data_hash+'
'); - if (_blctr > 4) {let leftPos = $(content).scrollLeft(); $(content).animate({scrollLeft: leftPos + 300}, 250);} - } - }; - csSocket.onerror = function (error) {console.log('WebSocket error: ' + error);}; - $('#admin-forms').empty(); - $('#admin-forms').append(_str); + $.when($.get('/fabric/getChainEvents')).done(function(_res) + { $('#body').append('

Get Chain events requested.

'); + let _host = (host_address.slice(0,9) === 'localhost') ? 'localhost' : host_address; + console.log('getChainEvents host_address: '+_host); }); } /** diff --git a/Chapter05/HTML/js/z2b-events.js b/Chapter05/HTML/js/z2b-events.js index f93de96..282f3ea 100644 --- a/Chapter05/HTML/js/z2b-events.js +++ b/Chapter05/HTML/js/z2b-events.js @@ -14,31 +14,79 @@ // z2c-events.js +'use strict'; + +let wsSocket; + +/** + * load the four initial user roles into a single page. + */ +function singleUX () +{ + let toLoad = 'singleUX.html'; + if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } + else{ + $.when($.get(toLoad)).done(function(_page) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } +} /** * load all of the members in the network for use in the different user experiences. This is a synchronous routine and is executed autormatically on web app start. * However, if this is a newly created network, then there are no members to retrieve and this will create four empty arrays */ function memberLoad () { - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - }); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + + }); +} +/** + * dropDummy() removes 'noop@dummy' from memberlist + * @param {String} _in - member id to ignore + */ +function dropDummy(_in) +{ + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} + return _a; } /** * load all of the members in the network for use in the different user experiences. This routine is designed for use if the network has been newly deployed and the web app was @@ -46,39 +94,190 @@ function memberLoad () */ function deferredMemberLoad() { - var d_prompts = $.Deferred(); - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - d_prompts.resolve(); - }).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + d_prompts.resolve(); + }).fail(d_prompts.reject); + return d_prompts.promise(); } /** * return an option list for use in an HTML '; - return _str; + return _str; +} +/** + * set up the server to listen for all events + */ +function goEventInitialize() +{ + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); +} + +/** + * @param {Event} _event - inbound Event + * @param {String} _id - subscriber target + * @param {String} _orderID - inbound order id + */ +function addNotification(_event, _id, _orderID) +{ + let method = 'addNotification'; + console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); + let type = getSubscriber(_id); + if (type === 'none') {return;} + switch(type) + { + case 'Buyer': + b_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(b_notify, b_alerts, b_count); + break; + case 'Seller': + s_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(s_notify, s_alerts, s_count); + break; + case 'Provider': + p_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(p_notify, p_alerts, p_count); + break; + case 'Shipper': + sh_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(sh_notify, sh_alerts, sh_count); + break; + case 'FinanceCo': + f_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(f_notify, f_alerts, f_count); + break; + default: + console.log(method+' default entered for: '+type); + break; + } +} +/** + * + * @param {jQuery} _target - jquery object to update + * @param {Array} _array - array of alerts for this member + * @param {jQuery} _count - jQuery object to hold alert count + */ +function toggleAlert(_target, _array, _count) +{ + if (_array.length < 1) + {$(_target).removeClass('on'); $(_target).addClass('off'); } + else {$(_count).empty(); $(_count).append(_array.length); + $(_target).removeClass('off'); $(_target).addClass('on'); } + +} +/** + * check to see if _id is subscribing + * @param {Integer} _id - member id to seek + * @returns {String} - type of member + */ +function getSubscriber(_id) +{ + let type = 'none'; + for (let each in subscribers){(function(_idx, _arr){if (_arr[_idx].id === _id){type=_arr[_idx].type;}})(each, subscribers);} + return(type); +} +/** + * subscribe to events + * @param {String} _type - member type + * @param {String} _id - member id + */ +function z2bSubscribe(_type, _id) +{ + subscribers.push({'type': _type, 'id': _id}); +} +/** + * Unsubscribe to events + * @param {String} _id - member id to remove + */ +function z2bUnSubscribe(_id) +{ + let _s1 = subscribers; + let _s2 = []; + for (let each in _s1) {(function(_idx, _arr){if (_arr[_idx] != _id){_s2.push(_arr[_idx]);}})(each, _s1);} + subscribers = _s2; +} +/** + * notifyMe + * @param {Array} _alerts - array of alerts + * @param {String} _id - orderID + * @returns {Boolean} - true if found, false if not found + */ +function notifyMe (_alerts, _id) +{ + let b_h = false; + for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} + return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
Hash: '+incoming.data.header.data_hash+'
'); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter05/HTML/js/z2b-initiate.js b/Chapter05/HTML/js/z2b-initiate.js index 8f676be..fd9a9d0 100644 --- a/Chapter05/HTML/js/z2b-initiate.js +++ b/Chapter05/HTML/js/z2b-initiate.js @@ -12,42 +12,53 @@ * limitations under the License. */ -// z2c-initiate.js -var connectionProfileName = "z2b-test-profile"; -var networkFile = "zerotoblockchain-network.bna" -var businessNetwork = "zerotoblockchain-network"; - -var buyers, sellers, providers, shippers; -var s_string, p_string, sh_string; - -var orderStatus = { - Created: {code: 1, text: 'Order Created'}, - Bought: {code: 2, text: 'Order Purchased'}, - Cancelled: {code: 3, text: 'Order Cancelled'}, - Ordered: {code: 4, text: 'Order Submitted to Provider'}, - ShipRequest: {code: 5, text: 'Shipping Requested'}, - Delivered: {code: 6, text: 'Order Delivered'}, - Delivering: {code: 15, text: 'Order being Delivered'}, - Backordered: {code: 7, text: 'Order Backordered'}, - Dispute: {code: 8, text: 'Order Disputed'}, - Resolve: {code: 9, text: 'Order Dispute Resolved'}, - PayRequest: {code: 10, text: 'Payment Requested'}, - Authorize: {code: 11, text: 'Payment Approved'}, - Paid: {code: 14, text: 'Payment Processed'}, - Refund: {code: 12, text: 'Order Refund Requested'}, - Refunded: {code: 13, text: 'Order Refunded'} +// z2b-initiate.js + +'use strict'; + +let connectionProfileName = 'z2b-test-profile'; +let networkFile = 'zerotoblockchain-network.bna'; +let businessNetwork = 'zerotoblockchain-network'; + +let host_address = window.location.host; + +let buyers = new Array(); +let sellers= new Array(); +let providers= new Array(); +let shippers= new Array(); + +let s_string, p_string, sh_string; + +let orderStatus = { + Created: {code: 1, text: 'Order Created'}, + Bought: {code: 2, text: 'Order Purchased'}, + Cancelled: {code: 3, text: 'Order Cancelled'}, + Ordered: {code: 4, text: 'Order Submitted to Provider'}, + ShipRequest: {code: 5, text: 'Shipping Requested'}, + Delivered: {code: 6, text: 'Order Delivered'}, + Delivering: {code: 15, text: 'Order being Delivered'}, + Backordered: {code: 7, text: 'Order Backordered'}, + Dispute: {code: 8, text: 'Order Disputed'}, + Resolve: {code: 9, text: 'Order Dispute Resolved'}, + PayRequest: {code: 10, text: 'Payment Requested'}, + Authorize: {code: 11, text: 'Payment Approved'}, + Paid: {code: 14, text: 'Payment Processed'}, + Refund: {code: 12, text: 'Order Refund Requested'}, + Refunded: {code: 13, text: 'Order Refunded'} }; /** * standard home page initialization routine * Refer to this by {@link initPage()}. */ - function initPage () +function initPage () { - // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English - goMultiLingual("US_English", "index"); - // singleUX loads the members already present in the network - memberLoad(); - // getChainEvents creates a web socket connection with the server and initiates blockchain event monitoring - getChainEvents(); + // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English + goMultiLingual('US_English', 'index'); + // singleUX loads the members already present in the network + memberLoad(); + // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring + getChainEvents(); + // get the asynch port + wsConnect(); } diff --git a/Chapter05/HTML/js/z2b-utilities.js b/Chapter05/HTML/js/z2b-utilities.js index ae1637f..3b137f0 100644 --- a/Chapter05/HTML/js/z2b-utilities.js +++ b/Chapter05/HTML/js/z2b-utilities.js @@ -6,68 +6,72 @@ * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, + * distributed under the License is distributed on an "AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -// z2c-utilities.js - +// z2b-utilities.js +'use strict'; /** * creates a set of utilities inside the named space: z2c * All utilities are accessed as z2c.functionName() * @namespace - z2c */ -languages = {}, // getSupportedLanguages -selectedLanguage = {}, -language = "", -textLocations = {}, // getTextLocations -textPrompts = {}, // getSelectedPromots +let languages = {}, // getSupportedLanguages + selectedLanguage = {}, + language = '', + textLocations = {}, // getTextLocations + textPrompts = {}, // getSelectedPromots + subscribers = new Array(); // subscribers to business events /** * get the value associated with a cookie named in the input * Refer to this by {@link getCookieValue}. * @param {String} _name - the name of the cookie to find -* @namespace +* @returns {String} - cookie value +* @namespace */ function getCookieValue(_name) { - var name = _name+"="; - var cookie_array= document.cookie.split(";"); - for (each in cookie_array) - { var c = cookie_array[each].trim(); - if(c.indexOf(name) == 0) return(c.substring(name.length, c.length)); - } - return(""); + let name = _name+'='; + let cookie_array= document.cookie.split(';'); + for (let each in cookie_array) + { + let c = cookie_array[each].trim(); + if(c.indexOf(name) === 0) {return(c.substring(name.length, c.length));} + } + return(''); } /** * trims a string by removing all leading and trailing spaces * trims the final period, if it exists, from a string. * Refer to this by {@link trimStrip}. -* @param {String} _string String to be trimmed and stripped of trailing period -* @namespace +* @param {String} _string - String to be trimmed and stripped of trailing period +* @returns {String} - trimmed string +* @namespace */ function trimStrip(_string) { - var str = _string.trim(); - var len = str.length; - if(str.endsWith(".")) {str=str.substring(0,len-1);} - return(str); + let str = _string.trim(); + let len = str.length; + if(str.endsWith('.')) {str=str.substring(0,len-1);} + return(str); } /** * replaces text on an html page based on the anchors and text provided in a JSON textPrompts object * Refer to this by {@link updatePage}. * @param {String} _page - a string representing the name of the html page to be updated -* @namespace +* @namespace */ function updatePage(_page) { - for (each in textPrompts[_page]){(function(_idx, _array) - {$("#"+_idx).empty();$("#"+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} + for (let each in textPrompts[_page]){(function(_idx, _array) + {$('#'+_idx).empty();$('#'+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} } /** @@ -75,7 +79,8 @@ function updatePage(_page) * Refer to this by {@link getDisplaytext}. * @param {String} _page - string representing the name of the html page to be updated * @param {String} _item - string representing the html named item to be updated -* @namespace +* @returns {String} - text to be placed on web page +* @namespace */ function getDisplaytext(_page, _item) {return (textPrompts[_page][_item]);} @@ -85,54 +90,56 @@ function getDisplaytext(_page, _item) * Refer to this by {@link goMultiLingual}. * @param {String} _language - language to be used in this session * @param {String} _page - string representing html page to be updated in the selected language -* @namespace +* @namespace */ function goMultiLingual(_language, _page) { language = _language; - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - {languages = _res; - selectedLanguage = languages[_language]; - var options = {}; options.language = _language; - $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) - {textLocations = _locations; - textPrompts = JSON.parse(_prompts[0]); - updatePage(_page); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + {languages = _res; + selectedLanguage = languages[_language]; + let options = {}; options.language = _language; + $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) + {textLocations = _locations; + textPrompts = JSON.parse(_prompts[0]); + updatePage(_page); + }); + let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • '} + })(each, _res); + } + _choices.append(_str); }); - var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); } /** * get SupportedLanguages returns an html menu object with available languages * Refer to this by {@link getSupportedLanguages}. -* @namespace +* @namespace */ function getSupportedLanguages() { - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - { - languages = _res; console.log(_res); var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + { + languages = _res; console.log(_res); let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • ';} + })(each, _res); + } + _choices.append(_str); + }); } /** * returns a JSON object with the pages and objects which support text replacement * Refer to this by {@link getTextLocations}. -* @namespace +* @namespace */ function getTextLocationsfunction () {$.when($.get('/api/getTextLocations')).done(function(_res){textLocations = _res; console.log(_res); });} @@ -140,38 +147,39 @@ function getTextLocationsfunction () /** * returns a JSON object with the text to be used to update identified pages and objects * Refer to this by {@link getSelectedPrompts}. -* @param {String} _inbound -* @namespace +* @param {String} _inbound - page or object to receive updated text +* @namespace */ function getSelectedPrompts(_inbound) { selectedLanguage=languages[_inbound]; - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); } /** * retrieves the prompts for the requested language from the server * Refer to this by {@link qOnSelectedPrompts}. * @param {String} _inbound - string representing the requested language -* @namespace +* @returns {Promise} - returns promise when selected prompts have been retrieved from server +* @namespace */ function qOnSelectedPrompts(_inbound) { - var d_prompts = $.Deferred(); - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); + return d_prompts.promise(); } /** * function to display the properties of an object using console.log * Refer to this by {@link displayObjectProperties}. * @param {Object} _obj - the object whose properties are to be displayed -* @namespace +* @namespace */ function displayObjectProperties(_obj) { - for(var propt in _obj){ console.log("object property: "+propt ); } + for(let propt in _obj){ console.log('object property: '+propt ); } } /** @@ -179,12 +187,12 @@ function displayObjectProperties(_obj) * Refer to this by {@link displayObjectValues}. * @param {String} _string - an arbitrary string to preface the printing of the object property name and value. often used to display the name of the object being printed * @param {Object} _object - the object to be introspected -* @namespace +* @namespace */ function displayObjectValues(_string, _object) { - for (prop in _object){ - console.log(_string+prop+": "+(((typeof(_object[prop]) == 'object') || (typeof(_object[prop]) == 'function')) ? typeof(_object[prop]) : _object[prop])); + for (let prop in _object){ + console.log(_string+prop+': '+(((typeof(_object[prop]) === 'object') || (typeof(_object[prop]) === 'function')) ? typeof(_object[prop]) : _object[prop])); } } @@ -201,124 +209,126 @@ function displayObjectValues(_string, _object) */ String.prototype.format = function(i, safe, arg) { +/** + * the format function added to String.prototype + * @returns {String} - returns original string with {x} replaced by provided text + */ + function format() { + let str = this, len = arguments.length+1; - function format() { - var str = this, len = arguments.length+1; - - // For each {0} {1} {n...} replace with the argument in that position. If - // the argument is an object or an array it will be stringified to JSON. - for (i=0; i < len; arg = arguments[i++]) { - safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; - str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + // For each {0} {1} {n...} replace with the argument in that position. If + // the argument is an object or an array it will be stringified to JSON. + for (i=0; i < len; arg = arguments[i++]) { + safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; + str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + } + return str; } - return str; - } - // Save a reference of what may already exist under the property native. - // Allows for doing something like: if("".format.native) { /* use native */ } - format.native = String.prototype.format; - - // Replace the prototype property - return format; + // Save a reference of what may already exist under the property native. + // Allows for doing something like: if(''.format.native) { /* use native */ } + format.native = String.prototype.format; + // Replace the prototype property + return format; }(); /** * display the hyperledger apis as currently understood * Refer to this by {@link showAPIDocs}. - * + * */ function showAPIDocs() { - $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) - { - var _target = $("#body"); - _target.empty(); _target.append(_page[0]); - displayAPI(_res[0]); - }); + $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) + { + let _target = $('#body'); + _target.empty(); _target.append(_page[0]); + displayAPI(_res[0]); + }); } /** - * - * @param {JSON} _api + * + * @param {JSON} _api * Refer to this by {@link displayAPI}. - * + * */ function displayAPI(_api) { - var _exports = _api.hfcExports; - var _classes = _api.hfcClasses; - var _eTarget = $("#hfc_exports"); - var _cTarget = $("#hfc_classes"); - var _str = ""; - for (each in _exports) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - _str += ""+_curObj+""+_arr[_idx][_curObj]+""; - })(each, _exports); - } - _eTarget.append(_str); - _str = ""; - for (each in _classes) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - for (every in _arr[_idx][_curObj[0]]){ - (function(_idx2, _arr2) - { - _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); - _str+= ""+_curObj[0]+""+_curObj2+""+_arr2[_idx2][_curObj2[0]]+""; - })(every, _arr[_idx][_curObj[0]]) - } - })(each, _classes); - } - _cTarget.append(_str); + let _exports = _api.hfcExports; + let _classes = _api.hfcClasses; + let _eTarget = $('#hfc_exports'); + let _cTarget = $('#hfc_classes'); + let _str = ''; + for (let each in _exports) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + _str += ''+_curObj+''+_arr[_idx][_curObj]+''; + })(each, _exports); + } + _eTarget.append(_str); + _str = ''; + for (let each in _classes) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + for (let every in _arr[_idx][_curObj[0]]){ + (function(_idx2, _arr2) + { + let _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); + _str+= ''+_curObj[0]+''+_curObj2+''+_arr2[_idx2][_curObj2[0]]+''; + })(every, _arr[_idx][_curObj[0]]); + } + })(each, _classes); + } + _cTarget.append(_str); } /** * format messages for display + * @param {String} _msg - text to be enclosed in html message format + * @returns {String} - html formatted message */ function formatMessage(_msg) {return '

    '+_msg+'

    ';} + /** - * get the web socket port + * closes all accordians in this div + * @param {String} target - formatted jQuery string pointing to div with all accordians to collapse */ -function getPort () +function accOff(target) { - if (msgPort == null) - { $.when($.get('/setup/getPort')).done(function (port){console.log('port is: '+port.port); msgPort = port.port;});} + let thisElement = $(target); + let childNodes = thisElement.children(); + for (let each in childNodes) + {let node = '#'+childNodes[each].id; + if (node !== '#') + { + if($(node).hasClass('on')) {$(node).removeClass('on');} + $(node).addClass('off'); + } + } } + /** * toggle an accordian window + * @param {String} _parent - Div holding all accordians + * @param {String} _body - Div which only appears when accordian is expanded + * @param {HTMLDiv} _header - Div which appears when accordian is collapsed */ function accToggle(_parent, _body, _header) { - var parent = "#"+_parent; - var body="#"+_body; - var header = _header; - if ($(body).hasClass("on")) - {$(body).removeClass("on"); $(body).addClass("off"); - $(parent).removeClass("on"); $(parent).addClass("off"); - }else - { - accOff(parent); - $(body).removeClass("off"); $(body).addClass("on"); - $(parent).removeClass("off"); $(parent).addClass("on"); - } -} -/** - * - */ -function accOff(target) -{ - var thisElement = $(target); - var childNodes = thisElement.children(); - for (each in childNodes) - {var node = "#"+childNodes[each].id; - if (node != '#') - { - if($(node).hasClass("on")) {$(node).removeClass("on");} - $(node).addClass("off"); - } - } + let parent = '#'+_parent; + let body='#'+_body; + if ($(body).hasClass('on')) + { + $(body).removeClass('on'); $(body).addClass('off'); + $(parent).removeClass('on'); $(parent).addClass('off'); + }else + { + accOff(parent); + $(body).removeClass('off'); $(body).addClass('on'); + $(parent).removeClass('off'); $(parent).addClass('on'); + } } diff --git a/Chapter05/controller/restapi/features/composer/Z2B_Services.js b/Chapter05/controller/restapi/features/composer/Z2B_Services.js index 21dbb85..c4f8aa4 100644 --- a/Chapter05/controller/restapi/features/composer/Z2B_Services.js +++ b/Chapter05/controller/restapi/features/composer/Z2B_Services.js @@ -13,16 +13,18 @@ */ 'use strict'; -var fs = require('fs'); -var path = require('path'); +let fs = require('fs'); +let path = require('path'); const sleep = require('sleep'); -const ws = require('websocket'); -const http = require('http'); +// const ws = require('websocket'); +// const http = require('http'); +// const url = require('url'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); const appEnv = cfenv.getAppEnv(); +const util = require('./Z2B_Utilities'); app.set('port', appEnv.port); @@ -37,7 +39,7 @@ app.set('port', appEnv.port); * @class * @memberof module:Z2Blockchain */ -var Z2Blockchain = { +let Z2Blockchain = { /** * create an empty order. This is used by any server side routine that needs to create an new @@ -105,8 +107,8 @@ var Z2Blockchain = { /** * update item quantity. used by the autoLoad process. * @param {item_number} _itemNo - item number to find - * @param {vendor_array} _itemArray - item array from order * @param {item_number} _qty - quantity to change * @utility + * @param {vendor_array} _itemArray - item array from order */ setItem: function (_itemNo, _qty, _itemArray) { @@ -115,46 +117,78 @@ var Z2Blockchain = { }, /** * supplemental routine to resubmit orders when MVCC_READ_CONFLICT encountered + * @param {object} _con - web socket connection * @param {transaction} _item - transaction to process * @param {order_object} _id - order id - * @param {bnc} businessNetworkConnection - already created business network connection + * @param {BusinessNetworkConnection} businessNetworkConnection - already created business network connection + * @returns {promise} promise */ loadTransaction: function (_con, _item, _id, businessNetworkConnection) { + let method = 'loadTransaction'; return businessNetworkConnection.submitTransaction(_item) .then(() => { - console.log('loadTransaction: order '+_id+' successfully added'); - _con.sendUTF('loadTransaction: order '+_id+' successfully added'); + console.log(method+': order '+_id+' successfully added '); + this.send(_con, 'Message', 'Order '+_id+' successfully added'); }) .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) + if (error.message.search('MVCC_READ_CONFLICT') !== -1) {sleep.sleep(5); - console.log(_id+" loadTransaction retrying submit transaction for: "+_id); - this.loadTransaction(_con,_item, _id, businessNetworkConnection); + console.log(_id+' loadTransaction retrying submit transaction for: '+_id); + this.loadTransaction(_con, _item, _id, businessNetworkConnection); } }); }, /** * add an order to a registry. This adds an Asset and does not execute a transaction - * @param {order_object} _order - order_object to process - * @param {assetRegistry} _registry - registry into which asset (order) should be placed + * @param {order_object} _con - websocket + * @param {assetRegistry} _order - order_object to process + * @param {networkTransaction} _registry - registry into which asset (order) should be placed * @param {networkTransaction} _createNew - transaction to be processed after order successfully added - * @param {businessNetworkConnection} _bnc - business network connection to use */ - addOrder: function (_con, _order, _registry, _createNew, _bnc) - { - return _registry.add(_order) - .then(() => { - this.loadTransaction(_con,_createNew, _order.orderNumber, _bnc); - }) - .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) - {console.log(_order.orderNumber+" addOrder retrying assetRegistry.add for: "+_order.orderNumber); - this.addOrder(_con,_order, _registry, _createNew, _bnc); - } - else {console.log('error with assetRegistry.add', error)} - }); + * @param {businessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +addOrder: function (_con, _order, _registry, _createNew, _bnc) +{ + let method = 'addOrder'; + return _registry.add(_order) + .then(() => { + this.loadTransaction(_con, _createNew, _order.orderNumber, _bnc); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(_order.orderNumber+' addOrder retrying assetRegistry.add for: '+_order.orderNumber); + this.addOrder(_con, _order, _registry, _createNew, _bnc); + } + else {console.log(method+' error with assetRegistry.add', error);} + }); }, +/** + * repeats the bind identity request + * @param {WebSocket} _con - order_object to process + * @param {String} _id - registry into which asset (order) should be placed + * @param {String} _cert - transaction to be processed after order successfully added + * @param {BusinessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +bindIdentity: function (_con, _id, _cert, _bnc) +{ + let method = 'bindIdentity'; + console.log(method+' retrying bindIdentity for: '+_id); + return _bnc.bindIdentity(_id, _cert) + .then(() => { + console.log(method+' Succeeded for: '+_id); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(' bindIdentity retrying _bnc.bindIdentity(_id, _cert) for: '+_id); + this.bindIdentity(_con, _id, _cert, _bnc); + } + else {console.log(method+' error with _bnc.bindIdentity(_id, _cert) for: '+_id+' with error: ', error);} + }); +}, + /** * saves the member table with ids and secrets * @param {array} _table - array of JSON objects to save to file @@ -166,23 +200,26 @@ var Z2Blockchain = { let _mem = '{"members": ['; for (let each in _table) {(function(_idx, _arr) - {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table)} + {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table);} _mem += ']}'; fs.writeFileSync(newFile, _mem, options); }, /** * saves the item table * @param {array} _table - array of JSON objects to save to file + * @param {JSON} _table - data to be saved */ - saveItemTable: function (_table) - { - let options = { flag : 'w' }; - let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); - let _mem = '{"items": ['; - for (let each in _table) - {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table)} - _mem += ']}'; - fs.writeFileSync(newFile, _mem, options); - }, +saveItemTable: function (_table) +{ + console.log('_table: ', _table); + let options = { flag : 'w' }; + let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); + let _mem = '{"items": ['; + for (let each in _table) + {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table);} + _mem += ']}'; + console.log('_mem: ', _mem); + fs.writeFileSync(newFile, _mem, options); +}, /** * update an empty order with 4 items. update the amount field based on the sum of the line items * @param {addItems} _inbound - Order created with factory.newResource(NS, 'Order',.orderNumber) @@ -205,7 +242,7 @@ var Z2Blockchain = { _arr[_idx].extendedPrice = _item.unitPrice*_arr[_idx].quantity; _amount += _arr[_idx].extendedPrice; _items.push(JSON.stringify(_arr[_idx])); - })(each, _inbound.items)} + })(each, _inbound.items);} return ({'items': _items, 'amount': _amount}); }, /** @@ -213,22 +250,23 @@ var Z2Blockchain = { * was not initially working. This function is no longer in use. * @param {Order} _order - the inbound Order item retrieved from a registry * @return JSON object order elements + * @return {Order} JSON object order elements * @function */ - getOrderData: function (_order) - { - let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', - 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; - var _obj = {}; - for (let each in orderElements){(function(_idx, _arr) - { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements)} - _obj.buyer = _order.buyer.$identifier; - _obj.seller = _order.seller.$identifier; - _obj.provider = _order.seller.$provider; - _obj.shipper = _order.seller.$shipper; - _obj.financeCo = _order.seller.$financeCo; - return (_obj); - }, +getOrderData: function (_order) +{ + let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', + 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; + let _obj = {}; + for (let each in orderElements){(function(_idx, _arr) + { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements);} + _obj.buyer = _order.buyer.$identifier; + _obj.seller = _order.seller.$identifier; + _obj.provider = _order.seller.$provider; + _obj.shipper = _order.seller.$shipper; + _obj.financeCo = _order.seller.$financeCo; + return (_obj); +}, /** * JSON object of available order status types and codes. This is used by nodejs @@ -252,67 +290,15 @@ var Z2Blockchain = { Refunded: {code: 13, text: 'Order Refunded'} }, /** - * the user experience is enhanced if the browser can be notified of aysnchronous events. - * the createMessateSockt function creates a web socket service to which the browser can - * attach. - * @param {integer} _port - port number to use for this socket connection - * @returns {websocket} - web socket connection to be used on the server side. - */ - m_connection: null, - m_socketAddr: null, - m_socket: null, - createMessageSocket: function (_port) - { - var port = (typeof(_port) == 'undefined' || _port == null) ? app.get('port')+1 : _port - if (this.m_socket == null) - { - this.m_socketAddr = port; - this.m_socket= new ws.server({httpServer: http.createServer().listen(this.m_socketAddr)}); - var _this = this; - this.m_socket.on('request', function(request) - { - _this.m_connection = request.accept(null, request.origin); - _this.m_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.m_connection.sendUTF('connected'); - _this.m_connection.on('close', function(m_connection) {console.log('m_connection closed'); }); - }); - }); - } - return {conn: this.m_connection, socket: this.m_socketAddr}; - }, -/** - * the cs_connection is used to display blockchain information to the web browser over - * a sepaarate port from the user experience socket. - * @returns {websocket} - web socket connection to be used on the server side. + * New code to support sending messages to socket clients + * @param {Object} _locals - shared variables and functions from index.js + * @param {String} type - type of event message to put on channel + * @param {Event} event - event message */ - - cs_connection: null, - cs_socketAddr: null, - cs_socket: null, - createChainSocket: function () - { - var port = app.get('port')+2; - if (this.cs_socket == null) - { - this.cs_socketAddr = port; - this.cs_socket= new ws.server({httpServer: http.createServer().listen(this.cs_socketAddr)}); - var _this = this; - this.cs_socket.on('request', function(request) - { - _this.cs_connection = request.accept(null, request.origin); - _this.cs_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.cs_connection.sendUTF('connected'); - _this.cs_connection.on('close', function(cs_connection) {console.log('cs_connection closed'); }); - }); - }); - } - return {conn: this.cs_connection, socket: this.cs_socketAddr}; - } - +send: function (_locals, type, event) +{ + _locals.processMessages({'type': type, 'data': event} ); } +}; module.exports = Z2Blockchain; \ No newline at end of file diff --git a/Chapter05/controller/restapi/features/composer/autoLoad.js b/Chapter05/controller/restapi/features/composer/autoLoad.js index ce3d81b..0206a5d 100644 --- a/Chapter05/controller/restapi/features/composer/autoLoad.js +++ b/Chapter05/controller/restapi/features/composer/autoLoad.js @@ -34,32 +34,13 @@ const financeCoID = 'easymoney@easymoneyinc.com'; const svc = require('./Z2B_Services'); const config = require('../../../env.json'); + /** * itemTable and memberTable are used by the server to reduce load time requests * for member secrets and item information */ let itemTable = new Array(); let memberTable = new Array(); -let socketAddr; - - - - - -/** - * getPort is used to return the port number for socket interactions so that - * the browser can receive asynchronous notifications of work in process. - * This helps the user understand the current status of the auto load process. - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * - * @function - */ -exports.getPort = function(req, res, next) { - let _conn = svc.createMessageSocket(); - res.send({'port': _conn.socket}); -}; /** * autoLoad reads the memberList.json file from the Startup folder and adds members, @@ -78,9 +59,9 @@ exports.autoLoad = function(req, res, next) { // connect to the network let businessNetworkConnection; let factory; let participant; - svc.createMessageSocket(); - socketAddr = svc.m_socketAddr; - let adminConnection = new AdminConnection(); +// svc.createMessageSocket(); +// socketAddr = svc.m_socketAddr; +let adminConnection = new AdminConnection(); // connection prior to V0.15 // adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW) // connection in v0.15 @@ -110,7 +91,7 @@ exports.autoLoad = function(req, res, next) { return participantRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { participant = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); @@ -118,7 +99,7 @@ exports.autoLoad = function(req, res, next) { participantRegistry.add(participant) .then(() => { console.log('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); - svc.m_connection.sendUTF('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); + svc.send(req.app.locals, 'Message', '['+_idx+'] '+_arr[_idx].companyName+' successfully added'); }) .then(() => { // an identity is required before a member can take action in the network. @@ -144,8 +125,10 @@ exports.autoLoad = function(req, res, next) { config.connectionProfile.keyValStore = _home+config.connectionProfile.keyValStore; let tempCard = new hlc_idCard(_meta, config.connectionProfile); return adminConnection.importCard(result.userID, tempCard) - .then ((_res) => { if (_res) {console.log('card updated');} else {console.log('card imported');} }) - .catch((error) => { + .then ((_res) => { + if (_res) {console.log('card updated');} else {console.log('card imported');} + }) + .catch((error) => { console.error('adminConnection.importCard failed. ',error.message); }); }) @@ -172,7 +155,7 @@ exports.autoLoad = function(req, res, next) { return assetRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { // first, an Order Object is created @@ -186,8 +169,8 @@ exports.autoLoad = function(req, res, next) { const createNew = factory.newTransaction(config.composer.NS, 'CreateOrder'); order.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); order.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); - order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummy'); - order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummy'); + order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummyProvider'); + order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummyShipper'); order.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.order = factory.newRelationship(config.composer.NS, 'Order', order.$identifier); @@ -199,7 +182,7 @@ exports.autoLoad = function(req, res, next) { .then(() => { // then a createOrder transaction is processed which uses the chaincode // establish the order with it's initial transaction state. - svc.loadTransaction(svc.m_connection, createNew, order.orderNumber, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, order.orderNumber, businessNetworkConnection); }) .catch((error) => { // in the development environment, because of how timing is set up, it is normal to @@ -207,7 +190,7 @@ exports.autoLoad = function(req, res, next) { // logical transaction error. if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log('AL: '+_arr[_idx].id+' retrying assetRegistry.add for: '+_arr[_idx].id); - svc.addOrder(svc.m_connection, order, assetRegistry, createNew, businessNetworkConnection); + svc.addOrder(req.app.locals, order, assetRegistry, createNew, businessNetworkConnection); } else {console.log('error with assetRegistry.add', error.message);} }); @@ -220,7 +203,7 @@ exports.autoLoad = function(req, res, next) { .catch((error) => {console.log('error with business network Connect', error.message);}); }) .catch((error) => {console.log('error with adminConnect', error.message);}); - res.send({'port': socketAddr}); + res.send({'result': 'Success'}); }; /** diff --git a/Chapter05/controller/restapi/features/composer/hlcClient.js b/Chapter05/controller/restapi/features/composer/hlcClient.js index bc5bfb6..a0a8559 100644 --- a/Chapter05/controller/restapi/features/composer/hlcClient.js +++ b/Chapter05/controller/restapi/features/composer/hlcClient.js @@ -18,11 +18,12 @@ let fs = require('fs'); let path = require('path'); const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition; -// const config = require('../../../env.json'); +const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; let itemTable = null; const svc = require('./Z2B_Services'); const financeCoID = 'easymoney@easymoneyinc.com'; +let bRegistered = false; /** * get orders for buyer with ID = _id @@ -244,7 +245,7 @@ exports.orderAction = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(' retrying assetRegistry.update for: '+req.body.orderNo); - svc.loadTransaction(svc.m_connection, updateOrder, req.body.orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, updateOrder, req.body.orderNo, businessNetworkConnection); } else {console.log(req.body.orderNo+' submitTransaction to update status to '+req.body.action+' failed with text: ',error.message);} @@ -329,7 +330,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else {console.log(orderNo+' submitTransaction failed with text: ',error.message);} @@ -338,7 +339,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else { @@ -353,7 +354,121 @@ exports.addOrder = function (req, res, next) { }); }) .catch((error) => { - console.log(orderNo+' business network connection failed: text',error.message); + console.log(method + ' : '+orderNo+' business network connection failed: text',error.message); res.send({'result': 'failed', 'error':' order '+orderNo+' add failed on on business network connection '+error.message}); }); }; +/** + * _monitor + * @param {WebSocket} _conn - web socket to use for member event posting + * @param {WebSocket} _f_conn - web sockect to use for FinanceCo event posting + * @param {Event} _event - the event just emitted + * + */ +function _monitor(locals, _event) +{ + let method = '_monitor'; + console.log(method+ ' _event received: '+_event.$type+' for Order: '+_event.orderID); + // create an event object and give it the event type, the orderID, the buyer id and the eventID + // send that event back to the requestor + let event = {}; + event.type = _event.$type; + event.orderID = _event.orderID; + event.ID = _event.buyerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + + // using switch/case logic, send events back to each participant who should be notified. + // for example, when a seller requests payment, they should be notified when the transaction has completed + // and the financeCo should be notified at the same time. + // so you would use the _conn connection to notify the seller and the + // _f_conn connection to notify the financeCo + + switch (_event.$type) + { + case 'Created': + break; + case 'Bought': + case 'PaymentRequested': + event.ID = _event.sellerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + event.ID = _event.financeCoID; + svc.send(locals, 'Alert',JSON.stringify(event)); + break; + case 'Ordered': + case 'Cancelled': + case 'Backordered': + event.ID = _event.sellerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + event.ID = _event.providerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + break; + case 'ShipRequest': + case 'DeliveryStarted': + case 'DeliveryCompleted': + event.ID = _event.sellerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + event.ID = _event.providerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + event.ID = _event.shipperID; + svc.send(locals, 'Alert',JSON.stringify(event)); + break; + case 'DisputeOpened': + case 'Resolved': + case 'Refunded': + case 'Paid': + event.ID = _event.sellerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + event.ID = _event.providerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + event.ID = _event.shipperID; + svc.send(locals, 'Alert',JSON.stringify(event)); + event.ID = _event.financeCoID; + svc.send(locals, 'Alert',JSON.stringify(event)); + break; + case 'PaymentAuthorized': + event.ID = _event.sellerID; + svc.send(locals, 'Alert',JSON.stringify(event)); + event.ID = _event.financeCoID; + svc.send(locals, 'Alert',JSON.stringify(event)); + break; + default: + break; + } + +} + +/** + * Register for all of the available Z2BEvents + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + * @returns {Object} - returns are via res.send +*/ +exports.init_z2bEvents = function (req, res, next) +{ + let method = 'init_z2bEvents'; + if (bRegistered) {res.send('Already Registered');} + else{ + bRegistered = true; +// svc.createAlertSocket(); + let businessNetworkConnection; + businessNetworkConnection = new BusinessNetworkConnection(); + businessNetworkConnection.setMaxListeners(50); + // + // v0.14 + // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // + // v0.15 + return businessNetworkConnection.connect(config.composer.adminCard) + .then(() => { + // using the businessNetworkConnection, start monitoring for events. + // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information + businessNetworkConnection.on('event', (event) => {_monitor(req.app.locals, event); }); + res.send('event registration complete'); + }).catch((error) => { + // if an error is encountered, log the error and send it back to the requestor + console.log(method+' business network connection failed'+error.message); + res.send(method+' business network connection failed'+error.message); + }); + } +}; diff --git a/Chapter05/controller/restapi/features/composer/queryBlockChain.js b/Chapter05/controller/restapi/features/composer/queryBlockChain.js index 9b6a396..75b67d3 100644 --- a/Chapter05/controller/restapi/features/composer/queryBlockChain.js +++ b/Chapter05/controller/restapi/features/composer/queryBlockChain.js @@ -12,8 +12,9 @@ * limitations under the License. */ -var path = require('path'); -var fs = require('fs'); +'use strict'; +let path = require('path'); +let fs = require('fs'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); @@ -24,10 +25,10 @@ const hfc = require('fabric-client'); const hfcEH = require('fabric-client/lib/EventHub'); const svc = require('./Z2B_Services'); -const util = require('./Z2B_Utilities'); -const financeCoID = 'easymoney@easymoneyinc.com'; +// const util = require('./Z2B_Utilities'); +// const financeCoID = 'easymoney@easymoneyinc.com'; const config = require('../../../env.json'); -var chainEvents = false; +let chainEvents = false; @@ -38,11 +39,13 @@ var chainEvents = false; * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainInfo = function(req, res, next) { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); - console.log(wallet_path); +exports.getChainInfo = function(req, res, next) +{ + let method='getChainInfo'; + let HOST_NAME = req.headers.host; + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); Promise.resolve().then(() => { // // As of 9/28/2017 there is a known and unresolved bug in HyperLedger Fabric @@ -61,29 +64,43 @@ exports.getChainInfo = function(req, res, next) { // change PeerAdmin in following line to adminID return client.getUserContext(config.composer.PeerAdmin, true);}) .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + if (user === null || user === undefined || user.isEnrolled() === false) + { console.error('User not defined, or not enrolled - error');} + if (HOST_NAME.slice(0,9) === 'localhost') + { + console.log(method+" running locally"); channel = client.newChannel(config.fabric.channelName); channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - }) + }else + { + console.log(method+" running remotely, not supported in Chapter 12"); + } + }) .then(() => { return channel.queryInfo() .then((blockchainInfo) => { if (blockchainInfo) { - res.send({"result": "success", "currentHash": blockchainInfo.currentBlockHash.toString("hex"), blockchain: blockchainInfo}); + res.send({'result': 'success', 'currentHash': blockchainInfo.currentBlockHash.toString('hex'), blockchain: blockchainInfo}); } else { console.log('response_payload is null'); - res.send({"result": "uncertain", "message": 'response_payload is null'}); + res.send({'result': 'uncertain', 'message': 'response_payload is null'}); } }) .catch((_err) => { - console.log("queryInfo failed with _err = ", _err); - res.send({"result": "failed", "message": _err.message}); - }); + console.log('queryInfo failed with _err = ', _err); + res.send({'result': 'failed', 'message': _err.message}); + }); }); - }); -} + }); +}; /** * get chain events @@ -92,37 +109,55 @@ exports.getChainInfo = function(req, res, next) { * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainEvents = function(req, res, next) { +exports.getChainEvents = function(req, res, next) +{ + let method = 'getChainEvents'; + let HOST_NAME = req.headers.host; if (chainEvents) {res.send({'port': svc.cs_socketAddr});} else { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); + Promise.resolve().then(() => { client = new hfc(); return hfc.newDefaultKeyValueStore({ path: wallet_path }) .then((wallet) => { client.setStateStore(wallet); // change PeerAdmin in following line to adminID - return client.getUserContext(config.composer.PeerAdmin, true);}) - .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} - channel = client.newChannel(config.fabric.channelName); - channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); - channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - // change Admin in following line to admin - var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); - var adminPEM = fs.readFileSync(pemPath).toString(); - var bcEvents = new hfcEH(client); - bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + return client.getUserContext(config.composer.PeerAdmin, true); + }) + .then((user) => { + if (user === null || user === undefined || user.isEnrolled() === false) + {console.error(method+': User not defined, or not enrolled - error');} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + // get the channel name + channel = client.newChannel(config.fabric.channelName); + //get the request URL for the Peer0 container + channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); + // get the orderer URL + channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); + // change Admin in following line to admin + var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); + var adminPEM = fs.readFileSync(pemPath).toString(); + var bcEvents = new hfcEH(client); + bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + bcEvents.registerBlockEvent( + function(event){svc.send(req.app.locals, 'BlockChain', event);}, + function(error){console.log(method+': registerBlockEvent error: ', error);} + ); bcEvents.connect(); - svc.createChainSocket(); - bcEvents.registerBlockEvent(function(event) {svc.cs_connection.sendUTF(JSON.stringify(event));}); - chainEvents = true; - res.send({'port': svc.cs_socketAddr}); - }) - }); - } -} + chainEvents = true; + res.send({'port': svc.cs_socketAddr}); + }) + .catch((err) => { console.log(method+': getUserContext failed: ',err);}); + }); + } +}; diff --git a/Chapter05/controller/restapi/router.js b/Chapter05/controller/restapi/router.js index a8e73d8..5d20aa6 100644 --- a/Chapter05/controller/restapi/router.js +++ b/Chapter05/controller/restapi/router.js @@ -13,26 +13,30 @@ */ -var express = require('express'); -var router = express.Router(); -var format = require('date-format'); +'use strict'; + +let express = require('express'); +let router = express.Router(); +let format = require('date-format'); + +let multi_lingual = require('./features/multi_lingual'); +let resources = require('./features/resources'); +let getCreds = require('./features/getCredentials'); +let hlcAdmin = require('./features/composer/hlcAdmin'); +let hlcClient = require('./features/composer/hlcClient'); +let setup = require('./features/composer/autoLoad'); +let hlcFabric = require('./features/composer/queryBlockChain'); -var multi_lingual = require('./features/multi_lingual'); -var resources = require('./features/resources'); -var getCreds = require('./features/getCredentials'); -var hlcAdmin = require('./features/composer/hlcAdmin'); -var hlcClient = require('./features/composer/hlcClient'); -var setup = require('./features/composer/autoLoad'); -var hlcFabric = require('./features/composer/queryBlockChain'); -router.post('/setup/autoLoad*', setup.autoLoad); -router.get('/setup/getPort*', setup.getPort); router.get('/fabric/getChainInfo', hlcFabric.getChainInfo); router.get('/fabric/getChainEvents', hlcFabric.getChainEvents); router.get('/fabric/getHistory', hlcAdmin.getHistory); +router.post('/setup/autoLoad*', setup.autoLoad); +router.get('/composer/client/initEventRegistry*', hlcClient.init_z2bEvents); + module.exports = router; -var count = 0; +let count = 0; /** * This is a request tracking function which logs to the terminal window each request coming in to the web serve and * increments a counter to allow the requests to be sequenced. diff --git a/Chapter05/favicon.ico b/Chapter05/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter05/favicon.ico and /dev/null differ diff --git a/Chapter05/index.js b/Chapter05/index.js index cb64e45..cf79cb7 100644 --- a/Chapter05/index.js +++ b/Chapter05/index.js @@ -14,25 +14,28 @@ /* * Zero to Blockchain */ -var express = require('express'); -var http = require('http'); -var https = require('https'); -var path = require('path'); -var fs = require('fs'); -var mime = require('mime'); -var bodyParser = require('body-parser'); -var cfenv = require('cfenv'); -var cookieParser = require('cookie-parser'); -var session = require('express-session'); +'use strict'; +const express = require('express'); +const http = require('http'); +const ws = require('websocket').server; +// const https = require('https'); +const path = require('path'); +const fs = require('fs'); +const mime = require('mime'); +const bodyParser = require('body-parser'); +const cfenv = require('cfenv'); -var vcapServices = require('vcap_services'); -var uuid = require('uuid'); -var env = require('./controller/envV2.json'); -var sessionSecret = env.sessionSecret; -var appEnv = cfenv.getAppEnv(); -var app = express(); -var busboy = require('connect-busboy'); +const cookieParser = require('cookie-parser'); +// const session = require('express-session'); + +// const vcapServices = require('vcap_services'); +// const uuid = require('uuid'); +const env = require('./controller/envV2.json'); +const sessionSecret = env.sessionSecret; +const appEnv = cfenv.getAppEnv(); +const app = express(); +const busboy = require('connect-busboy'); app.use(busboy()); // the session secret is a text string of arbitrary length which is @@ -49,7 +52,8 @@ app.use(cookieParser(sessionSecret)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); -app.set('appName', 'z2b-chapter05'); +app.set('appName', 'z2b-chapter12'); +process.title = 'Z2B-C12'; app.set('port', appEnv.port); app.set('views', path.join(__dirname + '/HTML')); @@ -59,15 +63,58 @@ app.use(express.static(__dirname + '/HTML')); app.use(bodyParser.json()); // Define your own router file in controller folder, export the router, add it into the index.js. -// app.use('/', require("./controller/yourOwnRouter")); -app.use('/', require("./controller/restapi/router")); +app.use('/', require('./controller/restapi/router')); -if (cfenv.getAppEnv().isLocal == true) - { var server = app.listen(app.get('port'), function() {console.log('Listening locally on port %d', server.address().port);}); } - else - { var server = app.listen(app.get('port'), function() {console.log('Listening remotely on port %d', server.address().port);}); } +let server = http.createServer(); +let clients = []; +app.locals.index=-1; +/** + * WebSocket server + */ +app.locals.wsServer = new ws({httpServer: server}); +app.locals.wsServer.on('request', function(request) +{ + // create a connection back to the requestor + app.locals.connection = request.accept(null, request.origin); + // we need to know client index to remove them on 'close' event + app.locals.index = clients.push(app.locals.connection) - 1; + // save the newly created connection. This is so that we can support many connections to many browsers simultaneously + console.log((new Date()) + ' Connection accepted.'); + app.locals.connection.on('message', function(message) + { let obj ={ime: (new Date()).getTime(),text: message.utf8Data}; + // broadcast message to all connected clients + let json = JSON.stringify({ type:'Message', data: obj }); + app.locals.processMessages(json); + }); + // user disconnected + app.locals.connection.on('close', function(_conn) { + console.log((new Date()) + ' Peer '+ app.locals.connection.socket._peername.address+':'+app.locals.connection.socket._peername.port+' disconnected with reason code: "'+_conn+'".'); + // remove user from the list of connected clients + // each browser connection has a unique address and socket combination + // When a browser session is disconnected, remove it from the array so we don't waste processing time sending messages to empty queues. + for (let each in clients) + {(function(_idx, _arr) + {if ((_arr[_idx].socket._peername.address === app.locals.connection.socket._peername.address) && (_arr[_idx].socket._peername.port === app.locals.connection.socket._peername.port)) + {clients.splice(_idx, 1);} + })(each, clients);} + }); +}); + +/** + * callable function to send messages over web socket + * @param {JSON} _jsonMsg - json formatted content to be sent as message data + */ +function processMessages (_jsonMsg) +{ + for (let i=0; i < clients.length; i++) {clients[i].send(JSON.stringify(_jsonMsg));} +} +// make the processMessages function available to all modules in this app. +app.locals.processMessages = processMessages; +// now set up the http server +server.on( 'request', app ); +server.listen(appEnv.port, function() {console.log('Listening locally on port %d', server.address().port);}); /** * load any file requested on the server * @param {express.req} req - the inbound request object from the client @@ -75,29 +122,17 @@ if (cfenv.getAppEnv().isLocal == true) * @function */ function loadSelectedFile(req, res) { - var uri = req.originalUrl; - var filename = __dirname + "/HTML" + uri; + let uri = req.originalUrl; + let filename = __dirname + '/HTML' + uri; fs.readFile(filename, function(err, data) { if (err) { console.log('Error loading ' + filename + ' error: ' + err); return res.status(500).send('Error loading ' + filename); } - var type = mime.lookup(filename); - res.setHeader('content-type', type); + let type = mime.lookup(filename); + res.setHeader('content-type', type); res.writeHead(200); res.end(data); }); } - -/** - * display using console.log the properties of each property in the inbound object - * @param {displayObjectProperties} _string - string name of object - * @param {displayObjectProperties} _object - the object to be parsed - * @utility - */ -function displayObjectValues (_string, _object) -{ - for (prop in _object){ - console.log(_string+prop+": "+(((typeof(_object[prop]) == 'object') || (typeof(_object[prop]) == 'function')) ? typeof(_object[prop]) : _object[prop]));} -} diff --git a/Chapter05/network/lib/sample.js b/Chapter05/network/lib/sample.js index e16ab45..cf652c9 100644 --- a/Chapter05/network/lib/sample.js +++ b/Chapter05/network/lib/sample.js @@ -160,11 +160,11 @@ function RequestPayment(purchase) { {purchase.order.status = JSON.stringify(orderStatus.PayRequest); purchase.order.financeCo = purchase.financeCo; purchase.order.paymentRequested = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -175,11 +175,11 @@ function AuthorizePayment(purchase) { if ((JSON.parse(purchase.order.status).text == orderStatus.PayRequest.text ) || (JSON.parse(purchase.order.status).text == orderStatus.Resolve.text )) {purchase.order.status = JSON.stringify(orderStatus.Authorize); purchase.order.approved = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -190,11 +190,11 @@ function Pay(purchase) { if (JSON.parse(purchase.order.status).text == orderStatus.Authorize.text ) {purchase.order.status = JSON.stringify(orderStatus.Paid); purchase.order.paid = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a dispute by the buyer diff --git a/Chapter06/Documentation/answers/composer/hlcClient_complete.js b/Chapter06/Documentation/answers/composer/hlcClient_complete.js index 00e58c9..e79d87b 100644 --- a/Chapter06/Documentation/answers/composer/hlcClient_complete.js +++ b/Chapter06/Documentation/answers/composer/hlcClient_complete.js @@ -18,11 +18,12 @@ let fs = require('fs'); let path = require('path'); const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition; -// const config = require('../../../env.json'); +const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; let itemTable = null; const svc = require('./Z2B_Services'); const financeCoID = 'easymoney@easymoneyinc.com'; +let bRegistered = false; /** * get orders for buyer with ID = _id @@ -218,7 +219,7 @@ exports.orderAction = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(' retrying assetRegistry.update for: '+req.body.orderNo); - svc.loadTransaction(svc.m_connection, updateOrder, req.body.orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, updateOrder, req.body.orderNo, businessNetworkConnection); } else {console.log(req.body.orderNo+' submitTransaction to update status to '+req.body.action+' failed with text: ',error.message);} @@ -303,7 +304,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else {console.log(orderNo+' submitTransaction failed with text: ',error.message);} @@ -312,7 +313,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else { @@ -327,7 +328,97 @@ exports.addOrder = function (req, res, next) { }); }) .catch((error) => { - console.log(orderNo+' business network connection failed: text',error.message); + console.log(method + ' : '+orderNo+' business network connection failed: text',error.message); res.send({'result': 'failed', 'error':' order '+orderNo+' add failed on on business network connection '+error.message}); }); }; + +/** + * _monitor + * @param {WebSocket} _conn - web socket to use for member event posting + * @param {WebSocket} _f_conn - web sockect to use for FinanceCo event posting + * @param {Event} _event - the event just emitted + * + */ +function _monitor(locals, _event) +{ + let method = '_monitor'; + console.log(method+ ' _event received: '+_event.$type+' for Order: '+_event.orderID); + // create an event object and give it the event type, the orderID, the buyer id and the eventID + // send that event back to the requestor + // ========> Your Code Goes Here <========= + + // using switch/case logic, send events back to each participant who should be notified. + // for example, when a seller requests payment, they should be notified when the transaction has completed + // and the financeCo should be notified at the same time. + // so you would use the _conn connection to notify the seller and the + // _f_conn connection to notify the financeCo + + switch (_event.$type) + { + case 'Created': + break; + case 'Bought': + case 'PaymentRequested': + // ========> Your Code Goes Here <========= + break; + case 'Ordered': + case 'Cancelled': + case 'Backordered': + // ========> Your Code Goes Here <========= + break; + case 'ShipRequest': + case 'DeliveryStarted': + case 'DeliveryCompleted': + // ========> Your Code Goes Here <========= + break; + case 'DisputeOpened': + case 'Resolved': + case 'Refunded': + case 'Paid': + // ========> Your Code Goes Here <========= + break; + case 'PaymentAuthorized': + // ========> Your Code Goes Here <========= + break; + default: + break; + } + +} + +/** + * Register for all of the available Z2BEvents + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + * @returns {Object} - returns are via res.send +*/ +exports.init_z2bEvents = function (req, res, next) +{ + let method = 'init_z2bEvents'; + if (bRegistered) {res.send('Already Registered');} + else{ + bRegistered = true; +// svc.createAlertSocket(); + let businessNetworkConnection; + businessNetworkConnection = new BusinessNetworkConnection(); + businessNetworkConnection.setMaxListeners(50); + // + // v0.14 + // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // + // v0.15 + return businessNetworkConnection.connect(config.composer.adminCard) + .then(() => { + // using the businessNetworkConnection, start monitoring for events. + // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information + businessNetworkConnection.on('event', (event) => {_monitor(req.app.locals, event); }); + res.send('event registration complete'); + }).catch((error) => { + // if an error is encountered, log the error and send it back to the requestor + console.log(method+' business network connection failed'+error.message); + res.send(method+' business network connection failed'+error.message); + }); + } +}; diff --git a/Chapter06/Documentation/answers/js/z2b-buyer_complete.js b/Chapter06/Documentation/answers/js/z2b-buyer_complete.js index 535f938..f1a1e93 100644 --- a/Chapter06/Documentation/answers/js/z2b-buyer_complete.js +++ b/Chapter06/Documentation/answers/js/z2b-buyer_complete.js @@ -15,6 +15,10 @@ // z2c-buyer.js 'use strict'; +let b_notify = '#buyer_notify'; +let b_count = '#buyer_count'; +let b_id = ''; +let b_alerts; let orderDiv = 'orderDiv'; let itemTable = {}; @@ -28,31 +32,37 @@ function loadBuyerUX () { // get the html page to load let toLoad = 'buyer.html'; - // get the port to use for web socket communications with the server - getPort(); // if (buyers.length === 0) then autoLoad() was not successfully run before this web app starts, so the sie of the buyer list is zero // assume user has run autoLoad and rebuild member list // if autoLoad not yet run, then member list length will still be zero if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupBuyer(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + { + setupBuyer(page); + }); } - else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupBuyer(page[0], port[0]);}); + else + { + $.when($.get(toLoad)).done(function (page) + { + setupBuyer(page); + }); } } - -function setupBuyer(page, port) -{ + + function setupBuyer(page) + { // empty the hetml element that will hold this page $('#body').empty(); $('#body').append(page); - // update the text on the page using the prompt data for the selected language + // empty the buyer alerts array + b_alerts = []; + // if there are no alerts, then remove the 'on' class and add the 'off' class + if (b_alerts.length === 0) + {$(b_notify).removeClass('on'); $(b_notify).addClass('off'); } + else {$(b_notify).removeClass('off'); $(b_notify).addClass('on'); } + // update the text on the page using the prompt data for the selected language updatePage('buyer'); - msgPort = port.port; - // connect to the web socket and tell the web socket where to display messages - wsDisplay('buyer_messages', msgPort); // enable the buttons to process an onClick event let _create = $('#newOrder'); let _list = $('#orderStatus'); @@ -67,8 +77,21 @@ function setupBuyer(page, port) } // display the name of the current buyer $('#company')[0].innerText = buyers[0].companyName; - // create a function to execute when the user selects a different buyer - $('#buyer').on('change', function() { _orderDiv.empty(); $('#buyer_messages').empty(); $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; }); + // save the current buyer id as b_id + b_id = buyers[0].id; + // subscribe to events + z2bSubscribe('Buyer', b_id); + // create a function to execute when the user selects a different buyer + $('#buyer').on('change', function() + { _orderDiv.empty(); $('#buyer_messages').empty(); + $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; + // unsubscribe the current buyer + z2bUnSubscribe(b_id); + // get the new buyer id + b_id = findMember($('#buyer').find(':selected').text(),buyers).id; + // subscribe the new buyer + z2bSubscribe('Buyer', b_id); + }); } /** @@ -97,7 +120,7 @@ function displayOrderForm() $('#amount').append('$'+totalAmount+'.00'); // build a select list for the items let _str = ''; - for (let each in itemTable){(function(_idx, _arr){_str+=''})(each, itemTable)} + for (let each in itemTable){(function(_idx, _arr){_str+='';})(each, itemTable);} $('#items').empty(); $('#items').append(_str); $('#cancelNewOrder').on('click', function (){_orderDiv.empty();}); @@ -185,8 +208,8 @@ function listOrders() * used by the listOrders() function * formats the orders for a buyer. Orders to be formatted are provided in the _orders array * output replaces the current contents of the html element identified by _target - * @param _target - string with div id prefaced by # - * @param _orders - array with order objects + * @param {String} _target - string with div id prefaced by # + * @param {Array} _orders - array with order objects */ function formatOrders(_target, _orders) { @@ -267,7 +290,7 @@ function formatOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+r_string+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.seller+findMember(_arr[_idx].seller.split('#')[1],sellers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+r_string+_button+''; _str+= '' for (let every in _arr[_idx].items) { @@ -286,18 +309,26 @@ function formatOrders(_target, _orders) // iterate through the page and make all of the different parts of the page active. // for (let each in _orders) - {(function(_idx, _arr) - { $('#b_btn_'+_idx).on('click', function () - { - let options = {}; - options.action = $('#b_action'+_idx).find(':selected').text(); - options.orderNo = $('#b_order'+_idx).text(); - options.participant = $('#buyer').val(); - if ((options.action === 'Dispute') || (options.action === 'Resolve')) {options.reason = $('#b_reason'+_idx).val();} - $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); - $.when($.post('/composer/client/orderAction', options)).done(function (_results) - { $('#buyer_messages').prepend(formatMessage(_results.result)); }); - }); - })(each, _orders) + {(function(_idx, _arr) + { $('#b_btn_'+_idx).on('click', function () + { + let options = {}; + options.action = $('#b_action'+_idx).find(':selected').text(); + options.orderNo = $('#b_order'+_idx).text(); + options.participant = $('#buyer').val(); + if ((options.action === 'Dispute') || (options.action === 'Resolve')) + {options.reason = $('#b_reason'+_idx).val();} + $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); + $.when($.post('/composer/client/orderAction', options)).done(function (_results) + { $('#buyer_messages').prepend(formatMessage(_results.result)); }); + }); + // use the notifyMe function to determine if this order is in the alert array. + // if it is, the highlight the $('#b_status'+_idx) html element by adding the 'highlight' class + if (notifyMe(b_alerts, _arr[_idx].id)) {$('#b_status'+_idx).addClass('highlight'); } + })(each, _orders); } + // reset the b_alerts array to a new array + b_alerts = new Array(); + // call the toggleAlerts function to reset the alert icon + toggleAlert($('#buyer_notify'), b_alerts, b_alerts.length); } \ No newline at end of file diff --git a/Chapter06/HTML/favicon.ico b/Chapter06/HTML/favicon.ico old mode 100755 new mode 100644 index fc9e25d..3dbe425 Binary files a/Chapter06/HTML/favicon.ico and b/Chapter06/HTML/favicon.ico differ diff --git a/Chapter06/HTML/js/z2b-admin.js b/Chapter06/HTML/js/z2b-admin.js index 67f421a..f3c3ffc 100644 --- a/Chapter06/HTML/js/z2b-admin.js +++ b/Chapter06/HTML/js/z2b-admin.js @@ -18,7 +18,6 @@ let creds; let connection; -let msgPort = null; let _blctr = 0; /** @@ -34,19 +33,6 @@ function loadAdminUX () listMemRegistries(); }); } -/** - * connect to the provided web socket - * @param {String} _target - location to post messages - * @param {Integer} _port - web socket port # - */ -function wsDisplay(_target, _port) -{ - let content = $('#'+_target); - let wsSocket = new WebSocket('ws://localhost:'+_port); - wsSocket.onopen = function () {wsSocket.send('connected to client');}; - wsSocket.onmessage = function (message) {content.append(formatMessage(message.data));}; - wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ' + error);}; -} /** * list the available business networks */ @@ -361,7 +347,7 @@ function preLoad() $('#body').empty(); let options = {}; $.when($.post('/setup/autoLoad', options)).done(function (_results) - { msgPort = _results.port; wsDisplay('body', msgPort); }); + { console.log('Autoload Initiated'); $('#body').append('

    Autoload Initiated

    '); }); } /** @@ -754,28 +740,9 @@ function getHistorian() */ function getChainEvents() { - $.when($.get('fabric/getChainEvents')).done(function(_res) - { let _str = '

    Get Chain events requested. Sending to port: '+_res.port+'

    '; - let content = $('#blockchain'); - let csSocket = new WebSocket('ws://localhost:'+_res.port); - csSocket.onopen = function () {csSocket.send('connected to client');}; - csSocket.onmessage = function (message) { - _blctr ++; - if (message.data !== 'connected') - {$(content).append('block '+JSON.parse(message.data).header.number+'
    Hash: '+JSON.parse(message.data).header.data_hash+'
    '); - if (_blctr > 4) {let leftPos = $(content).scrollLeft(); $(content).animate({scrollLeft: leftPos + 300}, 250);} - } - }; - csSocket.onerror = function (error) {console.log('WebSocket error: ' + error);}; - $('#admin-forms').empty(); - $('#admin-forms').append(_str); + $.when($.get('/fabric/getChainEvents')).done(function(_res) + { $('#body').append('

    Get Chain events requested.

    '); + let _host = (host_address.slice(0,9) === 'localhost') ? 'localhost' : host_address; + console.log('getChainEvents host_address: '+_host); }); -} -/** - * display blockchain updates - */ -function displayAdminUpdate() -{ - let toLoad = 'adminHelp.html'; - $.when($.get(toLoad)).done(function(_page){$('#admin-forms').empty(); $('#admin-forms').append(_page);}); } \ No newline at end of file diff --git a/Chapter06/HTML/js/z2b-buyer.js b/Chapter06/HTML/js/z2b-buyer.js index c91fdd5..4923fbc 100644 --- a/Chapter06/HTML/js/z2b-buyer.js +++ b/Chapter06/HTML/js/z2b-buyer.js @@ -15,6 +15,10 @@ // z2c-buyer.js 'use strict'; +let b_notify = '#buyer_notify'; +let b_count = '#buyer_count'; +let b_id = ''; +let b_alerts; let orderDiv = 'orderDiv'; let itemTable = {}; @@ -28,41 +32,66 @@ function loadBuyerUX () { // get the html page to load let toLoad = 'buyer.html'; - // get the port to use for web socket communications with the server - getPort(); // if (buyers.length === 0) then autoLoad() was not successfully run before this web app starts, so the sie of the buyer list is zero // assume user has run autoLoad and rebuild member list // if autoLoad not yet run, then member list length will still be zero if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupBuyer(page[0], port[0]);}); + { + console.log('deferredMemberLoad') + $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupBuyer(page);}); } - else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupBuyer(page[0], port[0]);}); + else + { + console.log('no deferredMemberLoad') + $.when($.get(toLoad)).done(function (page) + {setupBuyer(page);}); } } - -function setupBuyer(page, port) -{ + + function setupBuyer(page) + { // empty the hetml element that will hold this page - - // update the text on the page using the prompt data for the selected language + $('#body').empty(); + $('#body').append(page); + // empty the buyer alerts array + b_alerts = []; + // if there are no alerts, then remove the 'on' class and add the 'off' class + if (b_alerts.length === 0) + {$(b_notify).removeClass('on'); $(b_notify).addClass('off'); } + else {$(b_notify).removeClass('off'); $(b_notify).addClass('on'); } + // update the text on the page using the prompt data for the selected language updatePage('buyer'); - msgPort = port.port; - // connect to the web socket and tell the web socket where to display messages - // enable the buttons to process an onClick event - - // build the buyer select HTML element + let _create = $('#newOrder'); + let _list = $('#orderStatus'); + let _orderDiv = $('#'+orderDiv); + _create.on('click', function(){displayOrderForm();}); + _list.on('click', function(){listOrders();}); + $('#buyer').empty(); + // build the buer select HTML element for (let each in buyers) {(function(_idx, _arr) {$('#buyer').append('');})(each, buyers); } // display the name of the current buyer - - // create a function to execute when the user selects a different buyer - $('#buyer').on('change', function() { _orderDiv.empty(); $('#buyer_messages').empty(); $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; }); + var _loc = $('#company') + $('#company')[0].innerText = buyers[0].companyName; + // save the current buyer id as b_id + b_id = buyers[0].id; + // subscribe to events + z2bSubscribe('Buyer', b_id); + // create a function to execute when the user selects a different buyer + $('#buyer').on('change', function() + { _orderDiv.empty(); $('#buyer_messages').empty(); + $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; + // unsubscribe the current buyer + z2bUnSubscribe(b_id); + // get the new buyer id + b_id = findMember($('#buyer').find(':selected').text(),buyers).id; + // subscribe the new buyer + z2bSubscribe('Buyer', b_id); + }); } /** @@ -75,13 +104,26 @@ function displayOrderForm() // get the order creation web page and also get all of the items that a user can select $.when($.get(toLoad), $.get('/composer/client/getItemTable')).done(function (page, _items) { - + itemTable = _items[0].items; + let _orderDiv = $('#'+orderDiv); + _orderDiv.empty(); + _orderDiv.append(page[0]); // update the page with the appropriate text for the selected language - + updatePage('createOrder'); + $('#seller').empty(); // populate the seller HTML select object. This string was built during the memberLoad or deferredMemberLoad function call - + $('#seller').append(s_string); + $('#seller').val($('#seller option:first').val()); + $('#orderNo').append('xxx'); + $('#status').append('New Order'); + $('#today').append(new Date().toISOString()); + $('#amount').append('$'+totalAmount+'.00'); // build a select list for the items - + let _str = ''; + for (let each in itemTable){(function(_idx, _arr){_str+='';})(each, itemTable);} + $('#items').empty(); + $('#items').append(_str); + $('#cancelNewOrder').on('click', function (){_orderDiv.empty();}); // hide the submit new order function until an item has been selected $('#submitNewOrder').hide(); $('#submitNewOrder').on('click', function () @@ -96,19 +138,27 @@ function displayOrderForm() }); // function to call when an item has been selected $('#addItem').on('click', function () - { + { let _ptr = $('#items').find(':selected').val(); // remove the just selected item so that it cannot be added twice. - + $('#items').find(':selected').remove(); // build a new item detail row in the display window - + let _item = itemTable[_ptr]; + let len = newItems.length; + _str = ''; + $('#itemTable').append(_str); // set the initial item count to 1 - + $('#count'+len).val(1); // set the initial price to the price of one item - + $('#price'+len).append('$'+_item.unitPrice+'.00'); // add an entry into an array for this newly added item - + let _newItem = _item; + _newItem.extendedPrice = _item.unitPrice; + newItems[len] = _newItem; + newItems[len].quantity=1; + totalAmount += _newItem.extendedPrice; // update the order amount with this new item - + $('#amount').empty(); + $('#amount').append('$'+totalAmount+'.00'); // function to update item detail row and total amount if itemm count is changed $('#count'+len).on('change', function () {let len = this.id.substring(5); @@ -133,7 +183,7 @@ function listOrders() { let options = {}; // get the users email address - + options.id = $('#buyer').find(':selected').text(); // get their password from the server. This is clearly not something we would do in production, but enables us to demo more easily // $.when($.post('/composer/admin/getSecret', options)).done(function(_mem) // { @@ -188,41 +238,51 @@ function formatOrders(_target, _orders) r_string = '
    '+textPrompts.orderProcess.Dispute.prompt+''; break; case orderStatus.Delivered.code: - - break; + _date = _arr[_idx].delivered; + _action += ''; + r_string = '
    '+textPrompts.orderProcess.Dispute.prompt+''; + break; case orderStatus.Dispute.code: - - break; + _date = _arr[_idx].disputeOpened + '
    '+_arr[_idx].dispute; + _action += ''; + r_string = '
    '+textPrompts.orderProcess.Resolve.prompt+''; + break; case orderStatus.Resolve.code: - - break; + _date = _arr[_idx].disputeResolved + '
    '+_arr[_idx].resolve; + _action += ''; + break; case orderStatus.Created.code: - - break; + _date = _arr[_idx].created; + _action += '' + _action += '' + break; case orderStatus.Backordered.code: - - break; + _date = _arr[_idx].dateBackordered + '
    '+_arr[_idx].backorder; + _action += '' + break; case orderStatus.ShipRequest.code: - - break; + _date = _arr[_idx].requestShipment; + break; case orderStatus.Authorize.code: - - break; + _date = _arr[_idx].approved; + break; case orderStatus.Bought.code: - - break; + _date = _arr[_idx].bought; + _action += '' + break; case orderStatus.Delivering.code: - - break; + _date = _arr[_idx].delivering; + break; case orderStatus.Ordered.code: - - break; + _date = _arr[_idx].ordered; + _action += '' + break; case orderStatus.Cancelled.code: - - break; + _date = _arr[_idx].cancelled; + break; case orderStatus.Paid.code: - - break; + _date = _arr[_idx].paid; + break; default: break; } @@ -230,7 +290,7 @@ function formatOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    '+_item.itemNo+''+_item.itemDescription+'
    '; - _str += ''+_action+r_string+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.seller+findMember(_arr[_idx].seller.split('#')[1],sellers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+r_string+_button+''; _str+= '' for (let every in _arr[_idx].items) { @@ -249,18 +309,26 @@ function formatOrders(_target, _orders) // iterate through the page and make all of the different parts of the page active. // for (let each in _orders) - {(function(_idx, _arr) - { $('#b_btn_'+_idx).on('click', function () - { - let options = {}; - options.action = $('#b_action'+_idx).find(':selected').text(); - options.orderNo = $('#b_order'+_idx).text(); - options.participant = $('#buyer').val(); - if ((options.action === 'Dispute') || (options.action === 'Resolve')) {options.reason = $('#b_reason'+_idx).val();} - $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); - $.when($.post('/composer/client/orderAction', options)).done(function (_results) - { $('#buyer_messages').prepend(formatMessage(_results.result)); }); - }); - })(each, _orders) + {(function(_idx, _arr) + { $('#b_btn_'+_idx).on('click', function () + { + let options = {}; + options.action = $('#b_action'+_idx).find(':selected').text(); + options.orderNo = $('#b_order'+_idx).text(); + options.participant = $('#buyer').val(); + if ((options.action === 'Dispute') || (options.action === 'Resolve')) + {options.reason = $('#b_reason'+_idx).val();} + $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); + $.when($.post('/composer/client/orderAction', options)).done(function (_results) + { $('#buyer_messages').prepend(formatMessage(_results.result)); }); + }); + // use the notifyMe function to determine if this order is in the alert array. + // if it is, the highlight the $('#b_status'+_idx) html element by adding the 'highlight' class + if (notifyMe(b_alerts, _arr[_idx].id)) {$('#b_status'+_idx).addClass('highlight'); } + })(each, _orders); } + // reset the b_alerts array to a new array + b_alerts = new Array(); + // call the toggleAlerts function to reset the alert icon + toggleAlert($('#buyer_notify'), b_alerts, b_alerts.length); } \ No newline at end of file diff --git a/Chapter06/HTML/js/z2b-events.js b/Chapter06/HTML/js/z2b-events.js index 1b67217..282f3ea 100644 --- a/Chapter06/HTML/js/z2b-events.js +++ b/Chapter06/HTML/js/z2b-events.js @@ -14,31 +14,79 @@ // z2c-events.js +'use strict'; + +let wsSocket; + +/** + * load the four initial user roles into a single page. + */ +function singleUX () +{ + let toLoad = 'singleUX.html'; + if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } + else{ + $.when($.get(toLoad)).done(function(_page) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } +} /** * load all of the members in the network for use in the different user experiences. This is a synchronous routine and is executed autormatically on web app start. * However, if this is a newly created network, then there are no members to retrieve and this will create four empty arrays */ function memberLoad () { - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - }); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + + }); +} +/** + * dropDummy() removes 'noop@dummy' from memberlist + * @param {String} _in - member id to ignore + */ +function dropDummy(_in) +{ + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} + return _a; } /** * load all of the members in the network for use in the different user experiences. This routine is designed for use if the network has been newly deployed and the web app was @@ -46,40 +94,190 @@ function memberLoad () */ function deferredMemberLoad() { - var d_prompts = $.Deferred(); - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - console.log('buyers: ',_buyers); - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - d_prompts.resolve(); - }).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + d_prompts.resolve(); + }).fail(d_prompts.reject); + return d_prompts.promise(); } /** * return an option list for use in an HTML '; - return _str; + return _str; +} +/** + * set up the server to listen for all events + */ +function goEventInitialize() +{ + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); +} + +/** + * @param {Event} _event - inbound Event + * @param {String} _id - subscriber target + * @param {String} _orderID - inbound order id + */ +function addNotification(_event, _id, _orderID) +{ + let method = 'addNotification'; + console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); + let type = getSubscriber(_id); + if (type === 'none') {return;} + switch(type) + { + case 'Buyer': + b_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(b_notify, b_alerts, b_count); + break; + case 'Seller': + s_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(s_notify, s_alerts, s_count); + break; + case 'Provider': + p_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(p_notify, p_alerts, p_count); + break; + case 'Shipper': + sh_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(sh_notify, sh_alerts, sh_count); + break; + case 'FinanceCo': + f_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(f_notify, f_alerts, f_count); + break; + default: + console.log(method+' default entered for: '+type); + break; + } +} +/** + * + * @param {jQuery} _target - jquery object to update + * @param {Array} _array - array of alerts for this member + * @param {jQuery} _count - jQuery object to hold alert count + */ +function toggleAlert(_target, _array, _count) +{ + if (_array.length < 1) + {$(_target).removeClass('on'); $(_target).addClass('off'); } + else {$(_count).empty(); $(_count).append(_array.length); + $(_target).removeClass('off'); $(_target).addClass('on'); } + +} +/** + * check to see if _id is subscribing + * @param {Integer} _id - member id to seek + * @returns {String} - type of member + */ +function getSubscriber(_id) +{ + let type = 'none'; + for (let each in subscribers){(function(_idx, _arr){if (_arr[_idx].id === _id){type=_arr[_idx].type;}})(each, subscribers);} + return(type); +} +/** + * subscribe to events + * @param {String} _type - member type + * @param {String} _id - member id + */ +function z2bSubscribe(_type, _id) +{ + subscribers.push({'type': _type, 'id': _id}); +} +/** + * Unsubscribe to events + * @param {String} _id - member id to remove + */ +function z2bUnSubscribe(_id) +{ + let _s1 = subscribers; + let _s2 = []; + for (let each in _s1) {(function(_idx, _arr){if (_arr[_idx] != _id){_s2.push(_arr[_idx]);}})(each, _s1);} + subscribers = _s2; +} +/** + * notifyMe + * @param {Array} _alerts - array of alerts + * @param {String} _id - orderID + * @returns {Boolean} - true if found, false if not found + */ +function notifyMe (_alerts, _id) +{ + let b_h = false; + for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} + return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter06/HTML/js/z2b-initiate.js b/Chapter06/HTML/js/z2b-initiate.js index 290ef03..fd9a9d0 100644 --- a/Chapter06/HTML/js/z2b-initiate.js +++ b/Chapter06/HTML/js/z2b-initiate.js @@ -12,42 +12,53 @@ * limitations under the License. */ -// z2c-initiate.js -var connectionProfileName = "z2b-test-profile"; -var networkFile = "zerotoblockchain-network.bna" -var businessNetwork = "zerotoblockchain-network"; - -var buyers, sellers, providers, shippers; -var s_string, p_string, sh_string; - -var orderStatus = { - Created: {code: 1, text: 'Order Created'}, - Bought: {code: 2, text: 'Order Purchased'}, - Cancelled: {code: 3, text: 'Order Cancelled'}, - Ordered: {code: 4, text: 'Order Submitted to Provider'}, - ShipRequest: {code: 5, text: 'Shipping Requested'}, - Delivered: {code: 6, text: 'Order Delivered'}, - Delivering: {code: 15, text: 'Order being Delivered'}, - Backordered: {code: 7, text: 'Order Backordered'}, - Dispute: {code: 8, text: 'Order Disputed'}, - Resolve: {code: 9, text: 'Order Dispute Resolved'}, - PayRequest: {code: 10, text: 'Payment Requested'}, - Authorize: {code: 11, text: 'Payment Approved'}, - Paid: {code: 14, text: 'Payment Processed'}, - Refund: {code: 12, text: 'Order Refund Requested'}, - Refunded: {code: 13, text: 'Order Refunded'} +// z2b-initiate.js + +'use strict'; + +let connectionProfileName = 'z2b-test-profile'; +let networkFile = 'zerotoblockchain-network.bna'; +let businessNetwork = 'zerotoblockchain-network'; + +let host_address = window.location.host; + +let buyers = new Array(); +let sellers= new Array(); +let providers= new Array(); +let shippers= new Array(); + +let s_string, p_string, sh_string; + +let orderStatus = { + Created: {code: 1, text: 'Order Created'}, + Bought: {code: 2, text: 'Order Purchased'}, + Cancelled: {code: 3, text: 'Order Cancelled'}, + Ordered: {code: 4, text: 'Order Submitted to Provider'}, + ShipRequest: {code: 5, text: 'Shipping Requested'}, + Delivered: {code: 6, text: 'Order Delivered'}, + Delivering: {code: 15, text: 'Order being Delivered'}, + Backordered: {code: 7, text: 'Order Backordered'}, + Dispute: {code: 8, text: 'Order Disputed'}, + Resolve: {code: 9, text: 'Order Dispute Resolved'}, + PayRequest: {code: 10, text: 'Payment Requested'}, + Authorize: {code: 11, text: 'Payment Approved'}, + Paid: {code: 14, text: 'Payment Processed'}, + Refund: {code: 12, text: 'Order Refund Requested'}, + Refunded: {code: 13, text: 'Order Refunded'} }; /** * standard home page initialization routine * Refer to this by {@link initPage()}. */ - function initPage () +function initPage () { - // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English - goMultiLingual("US_English", "index"); - // singleUX loads the members already present in the network - memberLoad(); - // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring - getChainEvents(); + // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English + goMultiLingual('US_English', 'index'); + // singleUX loads the members already present in the network + memberLoad(); + // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring + getChainEvents(); + // get the asynch port + wsConnect(); } diff --git a/Chapter06/HTML/js/z2b-utilities.js b/Chapter06/HTML/js/z2b-utilities.js index ae1637f..3b137f0 100644 --- a/Chapter06/HTML/js/z2b-utilities.js +++ b/Chapter06/HTML/js/z2b-utilities.js @@ -6,68 +6,72 @@ * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, + * distributed under the License is distributed on an "AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -// z2c-utilities.js - +// z2b-utilities.js +'use strict'; /** * creates a set of utilities inside the named space: z2c * All utilities are accessed as z2c.functionName() * @namespace - z2c */ -languages = {}, // getSupportedLanguages -selectedLanguage = {}, -language = "", -textLocations = {}, // getTextLocations -textPrompts = {}, // getSelectedPromots +let languages = {}, // getSupportedLanguages + selectedLanguage = {}, + language = '', + textLocations = {}, // getTextLocations + textPrompts = {}, // getSelectedPromots + subscribers = new Array(); // subscribers to business events /** * get the value associated with a cookie named in the input * Refer to this by {@link getCookieValue}. * @param {String} _name - the name of the cookie to find -* @namespace +* @returns {String} - cookie value +* @namespace */ function getCookieValue(_name) { - var name = _name+"="; - var cookie_array= document.cookie.split(";"); - for (each in cookie_array) - { var c = cookie_array[each].trim(); - if(c.indexOf(name) == 0) return(c.substring(name.length, c.length)); - } - return(""); + let name = _name+'='; + let cookie_array= document.cookie.split(';'); + for (let each in cookie_array) + { + let c = cookie_array[each].trim(); + if(c.indexOf(name) === 0) {return(c.substring(name.length, c.length));} + } + return(''); } /** * trims a string by removing all leading and trailing spaces * trims the final period, if it exists, from a string. * Refer to this by {@link trimStrip}. -* @param {String} _string String to be trimmed and stripped of trailing period -* @namespace +* @param {String} _string - String to be trimmed and stripped of trailing period +* @returns {String} - trimmed string +* @namespace */ function trimStrip(_string) { - var str = _string.trim(); - var len = str.length; - if(str.endsWith(".")) {str=str.substring(0,len-1);} - return(str); + let str = _string.trim(); + let len = str.length; + if(str.endsWith('.')) {str=str.substring(0,len-1);} + return(str); } /** * replaces text on an html page based on the anchors and text provided in a JSON textPrompts object * Refer to this by {@link updatePage}. * @param {String} _page - a string representing the name of the html page to be updated -* @namespace +* @namespace */ function updatePage(_page) { - for (each in textPrompts[_page]){(function(_idx, _array) - {$("#"+_idx).empty();$("#"+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} + for (let each in textPrompts[_page]){(function(_idx, _array) + {$('#'+_idx).empty();$('#'+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} } /** @@ -75,7 +79,8 @@ function updatePage(_page) * Refer to this by {@link getDisplaytext}. * @param {String} _page - string representing the name of the html page to be updated * @param {String} _item - string representing the html named item to be updated -* @namespace +* @returns {String} - text to be placed on web page +* @namespace */ function getDisplaytext(_page, _item) {return (textPrompts[_page][_item]);} @@ -85,54 +90,56 @@ function getDisplaytext(_page, _item) * Refer to this by {@link goMultiLingual}. * @param {String} _language - language to be used in this session * @param {String} _page - string representing html page to be updated in the selected language -* @namespace +* @namespace */ function goMultiLingual(_language, _page) { language = _language; - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - {languages = _res; - selectedLanguage = languages[_language]; - var options = {}; options.language = _language; - $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) - {textLocations = _locations; - textPrompts = JSON.parse(_prompts[0]); - updatePage(_page); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + {languages = _res; + selectedLanguage = languages[_language]; + let options = {}; options.language = _language; + $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) + {textLocations = _locations; + textPrompts = JSON.parse(_prompts[0]); + updatePage(_page); + }); + let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • '} + })(each, _res); + } + _choices.append(_str); }); - var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); } /** * get SupportedLanguages returns an html menu object with available languages * Refer to this by {@link getSupportedLanguages}. -* @namespace +* @namespace */ function getSupportedLanguages() { - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - { - languages = _res; console.log(_res); var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + { + languages = _res; console.log(_res); let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • ';} + })(each, _res); + } + _choices.append(_str); + }); } /** * returns a JSON object with the pages and objects which support text replacement * Refer to this by {@link getTextLocations}. -* @namespace +* @namespace */ function getTextLocationsfunction () {$.when($.get('/api/getTextLocations')).done(function(_res){textLocations = _res; console.log(_res); });} @@ -140,38 +147,39 @@ function getTextLocationsfunction () /** * returns a JSON object with the text to be used to update identified pages and objects * Refer to this by {@link getSelectedPrompts}. -* @param {String} _inbound -* @namespace +* @param {String} _inbound - page or object to receive updated text +* @namespace */ function getSelectedPrompts(_inbound) { selectedLanguage=languages[_inbound]; - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); } /** * retrieves the prompts for the requested language from the server * Refer to this by {@link qOnSelectedPrompts}. * @param {String} _inbound - string representing the requested language -* @namespace +* @returns {Promise} - returns promise when selected prompts have been retrieved from server +* @namespace */ function qOnSelectedPrompts(_inbound) { - var d_prompts = $.Deferred(); - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); + return d_prompts.promise(); } /** * function to display the properties of an object using console.log * Refer to this by {@link displayObjectProperties}. * @param {Object} _obj - the object whose properties are to be displayed -* @namespace +* @namespace */ function displayObjectProperties(_obj) { - for(var propt in _obj){ console.log("object property: "+propt ); } + for(let propt in _obj){ console.log('object property: '+propt ); } } /** @@ -179,12 +187,12 @@ function displayObjectProperties(_obj) * Refer to this by {@link displayObjectValues}. * @param {String} _string - an arbitrary string to preface the printing of the object property name and value. often used to display the name of the object being printed * @param {Object} _object - the object to be introspected -* @namespace +* @namespace */ function displayObjectValues(_string, _object) { - for (prop in _object){ - console.log(_string+prop+": "+(((typeof(_object[prop]) == 'object') || (typeof(_object[prop]) == 'function')) ? typeof(_object[prop]) : _object[prop])); + for (let prop in _object){ + console.log(_string+prop+': '+(((typeof(_object[prop]) === 'object') || (typeof(_object[prop]) === 'function')) ? typeof(_object[prop]) : _object[prop])); } } @@ -201,124 +209,126 @@ function displayObjectValues(_string, _object) */ String.prototype.format = function(i, safe, arg) { +/** + * the format function added to String.prototype + * @returns {String} - returns original string with {x} replaced by provided text + */ + function format() { + let str = this, len = arguments.length+1; - function format() { - var str = this, len = arguments.length+1; - - // For each {0} {1} {n...} replace with the argument in that position. If - // the argument is an object or an array it will be stringified to JSON. - for (i=0; i < len; arg = arguments[i++]) { - safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; - str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + // For each {0} {1} {n...} replace with the argument in that position. If + // the argument is an object or an array it will be stringified to JSON. + for (i=0; i < len; arg = arguments[i++]) { + safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; + str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + } + return str; } - return str; - } - // Save a reference of what may already exist under the property native. - // Allows for doing something like: if("".format.native) { /* use native */ } - format.native = String.prototype.format; - - // Replace the prototype property - return format; + // Save a reference of what may already exist under the property native. + // Allows for doing something like: if(''.format.native) { /* use native */ } + format.native = String.prototype.format; + // Replace the prototype property + return format; }(); /** * display the hyperledger apis as currently understood * Refer to this by {@link showAPIDocs}. - * + * */ function showAPIDocs() { - $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) - { - var _target = $("#body"); - _target.empty(); _target.append(_page[0]); - displayAPI(_res[0]); - }); + $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) + { + let _target = $('#body'); + _target.empty(); _target.append(_page[0]); + displayAPI(_res[0]); + }); } /** - * - * @param {JSON} _api + * + * @param {JSON} _api * Refer to this by {@link displayAPI}. - * + * */ function displayAPI(_api) { - var _exports = _api.hfcExports; - var _classes = _api.hfcClasses; - var _eTarget = $("#hfc_exports"); - var _cTarget = $("#hfc_classes"); - var _str = ""; - for (each in _exports) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - _str += ""; - })(each, _exports); - } - _eTarget.append(_str); - _str = ""; - for (each in _classes) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - for (every in _arr[_idx][_curObj[0]]){ - (function(_idx2, _arr2) - { - _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); - _str+= ""; - })(every, _arr[_idx][_curObj[0]]) - } - })(each, _classes); - } - _cTarget.append(_str); + let _exports = _api.hfcExports; + let _classes = _api.hfcClasses; + let _eTarget = $('#hfc_exports'); + let _cTarget = $('#hfc_classes'); + let _str = ''; + for (let each in _exports) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + _str += ''; + })(each, _exports); + } + _eTarget.append(_str); + _str = ''; + for (let each in _classes) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + for (let every in _arr[_idx][_curObj[0]]){ + (function(_idx2, _arr2) + { + let _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); + _str+= ''; + })(every, _arr[_idx][_curObj[0]]); + } + })(each, _classes); + } + _cTarget.append(_str); } /** * format messages for display + * @param {String} _msg - text to be enclosed in html message format + * @returns {String} - html formatted message */ function formatMessage(_msg) {return '

    '+_msg+'

    ';} + /** - * get the web socket port + * closes all accordians in this div + * @param {String} target - formatted jQuery string pointing to div with all accordians to collapse */ -function getPort () +function accOff(target) { - if (msgPort == null) - { $.when($.get('/setup/getPort')).done(function (port){console.log('port is: '+port.port); msgPort = port.port;});} + let thisElement = $(target); + let childNodes = thisElement.children(); + for (let each in childNodes) + {let node = '#'+childNodes[each].id; + if (node !== '#') + { + if($(node).hasClass('on')) {$(node).removeClass('on');} + $(node).addClass('off'); + } + } } + /** * toggle an accordian window + * @param {String} _parent - Div holding all accordians + * @param {String} _body - Div which only appears when accordian is expanded + * @param {HTMLDiv} _header - Div which appears when accordian is collapsed */ function accToggle(_parent, _body, _header) { - var parent = "#"+_parent; - var body="#"+_body; - var header = _header; - if ($(body).hasClass("on")) - {$(body).removeClass("on"); $(body).addClass("off"); - $(parent).removeClass("on"); $(parent).addClass("off"); - }else - { - accOff(parent); - $(body).removeClass("off"); $(body).addClass("on"); - $(parent).removeClass("off"); $(parent).addClass("on"); - } -} -/** - * - */ -function accOff(target) -{ - var thisElement = $(target); - var childNodes = thisElement.children(); - for (each in childNodes) - {var node = "#"+childNodes[each].id; - if (node != '#') - { - if($(node).hasClass("on")) {$(node).removeClass("on");} - $(node).addClass("off"); - } - } + let parent = '#'+_parent; + let body='#'+_body; + if ($(body).hasClass('on')) + { + $(body).removeClass('on'); $(body).addClass('off'); + $(parent).removeClass('on'); $(parent).addClass('off'); + }else + { + accOff(parent); + $(body).removeClass('off'); $(body).addClass('on'); + $(parent).removeClass('off'); $(parent).addClass('on'); + } } diff --git a/Chapter06/controller/restapi/features/composer/Z2B_Services.js b/Chapter06/controller/restapi/features/composer/Z2B_Services.js index 21dbb85..c4f8aa4 100644 --- a/Chapter06/controller/restapi/features/composer/Z2B_Services.js +++ b/Chapter06/controller/restapi/features/composer/Z2B_Services.js @@ -13,16 +13,18 @@ */ 'use strict'; -var fs = require('fs'); -var path = require('path'); +let fs = require('fs'); +let path = require('path'); const sleep = require('sleep'); -const ws = require('websocket'); -const http = require('http'); +// const ws = require('websocket'); +// const http = require('http'); +// const url = require('url'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); const appEnv = cfenv.getAppEnv(); +const util = require('./Z2B_Utilities'); app.set('port', appEnv.port); @@ -37,7 +39,7 @@ app.set('port', appEnv.port); * @class * @memberof module:Z2Blockchain */ -var Z2Blockchain = { +let Z2Blockchain = { /** * create an empty order. This is used by any server side routine that needs to create an new @@ -105,8 +107,8 @@ var Z2Blockchain = { /** * update item quantity. used by the autoLoad process. * @param {item_number} _itemNo - item number to find - * @param {vendor_array} _itemArray - item array from order * @param {item_number} _qty - quantity to change * @utility + * @param {vendor_array} _itemArray - item array from order */ setItem: function (_itemNo, _qty, _itemArray) { @@ -115,46 +117,78 @@ var Z2Blockchain = { }, /** * supplemental routine to resubmit orders when MVCC_READ_CONFLICT encountered + * @param {object} _con - web socket connection * @param {transaction} _item - transaction to process * @param {order_object} _id - order id - * @param {bnc} businessNetworkConnection - already created business network connection + * @param {BusinessNetworkConnection} businessNetworkConnection - already created business network connection + * @returns {promise} promise */ loadTransaction: function (_con, _item, _id, businessNetworkConnection) { + let method = 'loadTransaction'; return businessNetworkConnection.submitTransaction(_item) .then(() => { - console.log('loadTransaction: order '+_id+' successfully added'); - _con.sendUTF('loadTransaction: order '+_id+' successfully added'); + console.log(method+': order '+_id+' successfully added '); + this.send(_con, 'Message', 'Order '+_id+' successfully added'); }) .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) + if (error.message.search('MVCC_READ_CONFLICT') !== -1) {sleep.sleep(5); - console.log(_id+" loadTransaction retrying submit transaction for: "+_id); - this.loadTransaction(_con,_item, _id, businessNetworkConnection); + console.log(_id+' loadTransaction retrying submit transaction for: '+_id); + this.loadTransaction(_con, _item, _id, businessNetworkConnection); } }); }, /** * add an order to a registry. This adds an Asset and does not execute a transaction - * @param {order_object} _order - order_object to process - * @param {assetRegistry} _registry - registry into which asset (order) should be placed + * @param {order_object} _con - websocket + * @param {assetRegistry} _order - order_object to process + * @param {networkTransaction} _registry - registry into which asset (order) should be placed * @param {networkTransaction} _createNew - transaction to be processed after order successfully added - * @param {businessNetworkConnection} _bnc - business network connection to use */ - addOrder: function (_con, _order, _registry, _createNew, _bnc) - { - return _registry.add(_order) - .then(() => { - this.loadTransaction(_con,_createNew, _order.orderNumber, _bnc); - }) - .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) - {console.log(_order.orderNumber+" addOrder retrying assetRegistry.add for: "+_order.orderNumber); - this.addOrder(_con,_order, _registry, _createNew, _bnc); - } - else {console.log('error with assetRegistry.add', error)} - }); + * @param {businessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +addOrder: function (_con, _order, _registry, _createNew, _bnc) +{ + let method = 'addOrder'; + return _registry.add(_order) + .then(() => { + this.loadTransaction(_con, _createNew, _order.orderNumber, _bnc); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(_order.orderNumber+' addOrder retrying assetRegistry.add for: '+_order.orderNumber); + this.addOrder(_con, _order, _registry, _createNew, _bnc); + } + else {console.log(method+' error with assetRegistry.add', error);} + }); }, +/** + * repeats the bind identity request + * @param {WebSocket} _con - order_object to process + * @param {String} _id - registry into which asset (order) should be placed + * @param {String} _cert - transaction to be processed after order successfully added + * @param {BusinessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +bindIdentity: function (_con, _id, _cert, _bnc) +{ + let method = 'bindIdentity'; + console.log(method+' retrying bindIdentity for: '+_id); + return _bnc.bindIdentity(_id, _cert) + .then(() => { + console.log(method+' Succeeded for: '+_id); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(' bindIdentity retrying _bnc.bindIdentity(_id, _cert) for: '+_id); + this.bindIdentity(_con, _id, _cert, _bnc); + } + else {console.log(method+' error with _bnc.bindIdentity(_id, _cert) for: '+_id+' with error: ', error);} + }); +}, + /** * saves the member table with ids and secrets * @param {array} _table - array of JSON objects to save to file @@ -166,23 +200,26 @@ var Z2Blockchain = { let _mem = '{"members": ['; for (let each in _table) {(function(_idx, _arr) - {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table)} + {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table);} _mem += ']}'; fs.writeFileSync(newFile, _mem, options); }, /** * saves the item table * @param {array} _table - array of JSON objects to save to file + * @param {JSON} _table - data to be saved */ - saveItemTable: function (_table) - { - let options = { flag : 'w' }; - let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); - let _mem = '{"items": ['; - for (let each in _table) - {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table)} - _mem += ']}'; - fs.writeFileSync(newFile, _mem, options); - }, +saveItemTable: function (_table) +{ + console.log('_table: ', _table); + let options = { flag : 'w' }; + let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); + let _mem = '{"items": ['; + for (let each in _table) + {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table);} + _mem += ']}'; + console.log('_mem: ', _mem); + fs.writeFileSync(newFile, _mem, options); +}, /** * update an empty order with 4 items. update the amount field based on the sum of the line items * @param {addItems} _inbound - Order created with factory.newResource(NS, 'Order',.orderNumber) @@ -205,7 +242,7 @@ var Z2Blockchain = { _arr[_idx].extendedPrice = _item.unitPrice*_arr[_idx].quantity; _amount += _arr[_idx].extendedPrice; _items.push(JSON.stringify(_arr[_idx])); - })(each, _inbound.items)} + })(each, _inbound.items);} return ({'items': _items, 'amount': _amount}); }, /** @@ -213,22 +250,23 @@ var Z2Blockchain = { * was not initially working. This function is no longer in use. * @param {Order} _order - the inbound Order item retrieved from a registry * @return JSON object order elements + * @return {Order} JSON object order elements * @function */ - getOrderData: function (_order) - { - let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', - 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; - var _obj = {}; - for (let each in orderElements){(function(_idx, _arr) - { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements)} - _obj.buyer = _order.buyer.$identifier; - _obj.seller = _order.seller.$identifier; - _obj.provider = _order.seller.$provider; - _obj.shipper = _order.seller.$shipper; - _obj.financeCo = _order.seller.$financeCo; - return (_obj); - }, +getOrderData: function (_order) +{ + let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', + 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; + let _obj = {}; + for (let each in orderElements){(function(_idx, _arr) + { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements);} + _obj.buyer = _order.buyer.$identifier; + _obj.seller = _order.seller.$identifier; + _obj.provider = _order.seller.$provider; + _obj.shipper = _order.seller.$shipper; + _obj.financeCo = _order.seller.$financeCo; + return (_obj); +}, /** * JSON object of available order status types and codes. This is used by nodejs @@ -252,67 +290,15 @@ var Z2Blockchain = { Refunded: {code: 13, text: 'Order Refunded'} }, /** - * the user experience is enhanced if the browser can be notified of aysnchronous events. - * the createMessateSockt function creates a web socket service to which the browser can - * attach. - * @param {integer} _port - port number to use for this socket connection - * @returns {websocket} - web socket connection to be used on the server side. - */ - m_connection: null, - m_socketAddr: null, - m_socket: null, - createMessageSocket: function (_port) - { - var port = (typeof(_port) == 'undefined' || _port == null) ? app.get('port')+1 : _port - if (this.m_socket == null) - { - this.m_socketAddr = port; - this.m_socket= new ws.server({httpServer: http.createServer().listen(this.m_socketAddr)}); - var _this = this; - this.m_socket.on('request', function(request) - { - _this.m_connection = request.accept(null, request.origin); - _this.m_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.m_connection.sendUTF('connected'); - _this.m_connection.on('close', function(m_connection) {console.log('m_connection closed'); }); - }); - }); - } - return {conn: this.m_connection, socket: this.m_socketAddr}; - }, -/** - * the cs_connection is used to display blockchain information to the web browser over - * a sepaarate port from the user experience socket. - * @returns {websocket} - web socket connection to be used on the server side. + * New code to support sending messages to socket clients + * @param {Object} _locals - shared variables and functions from index.js + * @param {String} type - type of event message to put on channel + * @param {Event} event - event message */ - - cs_connection: null, - cs_socketAddr: null, - cs_socket: null, - createChainSocket: function () - { - var port = app.get('port')+2; - if (this.cs_socket == null) - { - this.cs_socketAddr = port; - this.cs_socket= new ws.server({httpServer: http.createServer().listen(this.cs_socketAddr)}); - var _this = this; - this.cs_socket.on('request', function(request) - { - _this.cs_connection = request.accept(null, request.origin); - _this.cs_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.cs_connection.sendUTF('connected'); - _this.cs_connection.on('close', function(cs_connection) {console.log('cs_connection closed'); }); - }); - }); - } - return {conn: this.cs_connection, socket: this.cs_socketAddr}; - } - +send: function (_locals, type, event) +{ + _locals.processMessages({'type': type, 'data': event} ); } +}; module.exports = Z2Blockchain; \ No newline at end of file diff --git a/Chapter06/controller/restapi/features/composer/autoLoad.js b/Chapter06/controller/restapi/features/composer/autoLoad.js index ce3d81b..0206a5d 100644 --- a/Chapter06/controller/restapi/features/composer/autoLoad.js +++ b/Chapter06/controller/restapi/features/composer/autoLoad.js @@ -34,32 +34,13 @@ const financeCoID = 'easymoney@easymoneyinc.com'; const svc = require('./Z2B_Services'); const config = require('../../../env.json'); + /** * itemTable and memberTable are used by the server to reduce load time requests * for member secrets and item information */ let itemTable = new Array(); let memberTable = new Array(); -let socketAddr; - - - - - -/** - * getPort is used to return the port number for socket interactions so that - * the browser can receive asynchronous notifications of work in process. - * This helps the user understand the current status of the auto load process. - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * - * @function - */ -exports.getPort = function(req, res, next) { - let _conn = svc.createMessageSocket(); - res.send({'port': _conn.socket}); -}; /** * autoLoad reads the memberList.json file from the Startup folder and adds members, @@ -78,9 +59,9 @@ exports.autoLoad = function(req, res, next) { // connect to the network let businessNetworkConnection; let factory; let participant; - svc.createMessageSocket(); - socketAddr = svc.m_socketAddr; - let adminConnection = new AdminConnection(); +// svc.createMessageSocket(); +// socketAddr = svc.m_socketAddr; +let adminConnection = new AdminConnection(); // connection prior to V0.15 // adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW) // connection in v0.15 @@ -110,7 +91,7 @@ exports.autoLoad = function(req, res, next) { return participantRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { participant = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); @@ -118,7 +99,7 @@ exports.autoLoad = function(req, res, next) { participantRegistry.add(participant) .then(() => { console.log('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); - svc.m_connection.sendUTF('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); + svc.send(req.app.locals, 'Message', '['+_idx+'] '+_arr[_idx].companyName+' successfully added'); }) .then(() => { // an identity is required before a member can take action in the network. @@ -144,8 +125,10 @@ exports.autoLoad = function(req, res, next) { config.connectionProfile.keyValStore = _home+config.connectionProfile.keyValStore; let tempCard = new hlc_idCard(_meta, config.connectionProfile); return adminConnection.importCard(result.userID, tempCard) - .then ((_res) => { if (_res) {console.log('card updated');} else {console.log('card imported');} }) - .catch((error) => { + .then ((_res) => { + if (_res) {console.log('card updated');} else {console.log('card imported');} + }) + .catch((error) => { console.error('adminConnection.importCard failed. ',error.message); }); }) @@ -172,7 +155,7 @@ exports.autoLoad = function(req, res, next) { return assetRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { // first, an Order Object is created @@ -186,8 +169,8 @@ exports.autoLoad = function(req, res, next) { const createNew = factory.newTransaction(config.composer.NS, 'CreateOrder'); order.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); order.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); - order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummy'); - order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummy'); + order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummyProvider'); + order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummyShipper'); order.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.order = factory.newRelationship(config.composer.NS, 'Order', order.$identifier); @@ -199,7 +182,7 @@ exports.autoLoad = function(req, res, next) { .then(() => { // then a createOrder transaction is processed which uses the chaincode // establish the order with it's initial transaction state. - svc.loadTransaction(svc.m_connection, createNew, order.orderNumber, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, order.orderNumber, businessNetworkConnection); }) .catch((error) => { // in the development environment, because of how timing is set up, it is normal to @@ -207,7 +190,7 @@ exports.autoLoad = function(req, res, next) { // logical transaction error. if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log('AL: '+_arr[_idx].id+' retrying assetRegistry.add for: '+_arr[_idx].id); - svc.addOrder(svc.m_connection, order, assetRegistry, createNew, businessNetworkConnection); + svc.addOrder(req.app.locals, order, assetRegistry, createNew, businessNetworkConnection); } else {console.log('error with assetRegistry.add', error.message);} }); @@ -220,7 +203,7 @@ exports.autoLoad = function(req, res, next) { .catch((error) => {console.log('error with business network Connect', error.message);}); }) .catch((error) => {console.log('error with adminConnect', error.message);}); - res.send({'port': socketAddr}); + res.send({'result': 'Success'}); }; /** diff --git a/Chapter06/controller/restapi/features/composer/hlcAdmin.js b/Chapter06/controller/restapi/features/composer/hlcAdmin.js index 8e9e8b9..46b188c 100644 --- a/Chapter06/controller/restapi/features/composer/hlcAdmin.js +++ b/Chapter06/controller/restapi/features/composer/hlcAdmin.js @@ -24,8 +24,7 @@ const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefi const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; -// const svc = require('./Z2B_Services'); -// const mod = 'hlcAdmin.js'; + /** * display the admin and network info diff --git a/Chapter06/controller/restapi/features/composer/queryBlockChain.js b/Chapter06/controller/restapi/features/composer/queryBlockChain.js index 9b6a396..75b67d3 100644 --- a/Chapter06/controller/restapi/features/composer/queryBlockChain.js +++ b/Chapter06/controller/restapi/features/composer/queryBlockChain.js @@ -12,8 +12,9 @@ * limitations under the License. */ -var path = require('path'); -var fs = require('fs'); +'use strict'; +let path = require('path'); +let fs = require('fs'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); @@ -24,10 +25,10 @@ const hfc = require('fabric-client'); const hfcEH = require('fabric-client/lib/EventHub'); const svc = require('./Z2B_Services'); -const util = require('./Z2B_Utilities'); -const financeCoID = 'easymoney@easymoneyinc.com'; +// const util = require('./Z2B_Utilities'); +// const financeCoID = 'easymoney@easymoneyinc.com'; const config = require('../../../env.json'); -var chainEvents = false; +let chainEvents = false; @@ -38,11 +39,13 @@ var chainEvents = false; * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainInfo = function(req, res, next) { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); - console.log(wallet_path); +exports.getChainInfo = function(req, res, next) +{ + let method='getChainInfo'; + let HOST_NAME = req.headers.host; + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); Promise.resolve().then(() => { // // As of 9/28/2017 there is a known and unresolved bug in HyperLedger Fabric @@ -61,29 +64,43 @@ exports.getChainInfo = function(req, res, next) { // change PeerAdmin in following line to adminID return client.getUserContext(config.composer.PeerAdmin, true);}) .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + if (user === null || user === undefined || user.isEnrolled() === false) + { console.error('User not defined, or not enrolled - error');} + if (HOST_NAME.slice(0,9) === 'localhost') + { + console.log(method+" running locally"); channel = client.newChannel(config.fabric.channelName); channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - }) + }else + { + console.log(method+" running remotely, not supported in Chapter 12"); + } + }) .then(() => { return channel.queryInfo() .then((blockchainInfo) => { if (blockchainInfo) { - res.send({"result": "success", "currentHash": blockchainInfo.currentBlockHash.toString("hex"), blockchain: blockchainInfo}); + res.send({'result': 'success', 'currentHash': blockchainInfo.currentBlockHash.toString('hex'), blockchain: blockchainInfo}); } else { console.log('response_payload is null'); - res.send({"result": "uncertain", "message": 'response_payload is null'}); + res.send({'result': 'uncertain', 'message': 'response_payload is null'}); } }) .catch((_err) => { - console.log("queryInfo failed with _err = ", _err); - res.send({"result": "failed", "message": _err.message}); - }); + console.log('queryInfo failed with _err = ', _err); + res.send({'result': 'failed', 'message': _err.message}); + }); }); - }); -} + }); +}; /** * get chain events @@ -92,37 +109,55 @@ exports.getChainInfo = function(req, res, next) { * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainEvents = function(req, res, next) { +exports.getChainEvents = function(req, res, next) +{ + let method = 'getChainEvents'; + let HOST_NAME = req.headers.host; if (chainEvents) {res.send({'port': svc.cs_socketAddr});} else { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); + Promise.resolve().then(() => { client = new hfc(); return hfc.newDefaultKeyValueStore({ path: wallet_path }) .then((wallet) => { client.setStateStore(wallet); // change PeerAdmin in following line to adminID - return client.getUserContext(config.composer.PeerAdmin, true);}) - .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} - channel = client.newChannel(config.fabric.channelName); - channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); - channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - // change Admin in following line to admin - var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); - var adminPEM = fs.readFileSync(pemPath).toString(); - var bcEvents = new hfcEH(client); - bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + return client.getUserContext(config.composer.PeerAdmin, true); + }) + .then((user) => { + if (user === null || user === undefined || user.isEnrolled() === false) + {console.error(method+': User not defined, or not enrolled - error');} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + // get the channel name + channel = client.newChannel(config.fabric.channelName); + //get the request URL for the Peer0 container + channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); + // get the orderer URL + channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); + // change Admin in following line to admin + var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); + var adminPEM = fs.readFileSync(pemPath).toString(); + var bcEvents = new hfcEH(client); + bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + bcEvents.registerBlockEvent( + function(event){svc.send(req.app.locals, 'BlockChain', event);}, + function(error){console.log(method+': registerBlockEvent error: ', error);} + ); bcEvents.connect(); - svc.createChainSocket(); - bcEvents.registerBlockEvent(function(event) {svc.cs_connection.sendUTF(JSON.stringify(event));}); - chainEvents = true; - res.send({'port': svc.cs_socketAddr}); - }) - }); - } -} + chainEvents = true; + res.send({'port': svc.cs_socketAddr}); + }) + .catch((err) => { console.log(method+': getUserContext failed: ',err);}); + }); + } +}; diff --git a/Chapter06/controller/restapi/router.js b/Chapter06/controller/restapi/router.js index 6fa15bd..14883e7 100644 --- a/Chapter06/controller/restapi/router.js +++ b/Chapter06/controller/restapi/router.js @@ -25,13 +25,15 @@ let hlcAdmin = require('./features/composer/hlcAdmin'); let hlcClient = require('./features/composer/hlcClient'); let setup = require('./features/composer/autoLoad'); let hlcFabric = require('./features/composer/queryBlockChain'); -router.post('/setup/autoLoad*', setup.autoLoad); -router.get('/setup/getPort*', setup.getPort); + router.get('/fabric/getChainInfo', hlcFabric.getChainInfo); router.get('/fabric/getChainEvents', hlcFabric.getChainEvents); router.get('/fabric/getHistory', hlcAdmin.getHistory); +router.post('/setup/autoLoad*', setup.autoLoad); +router.get('/composer/client/initEventRegistry*', hlcClient.init_z2bEvents); + module.exports = router; let count = 0; /** @@ -71,6 +73,7 @@ router.get('/composer/admin/getAllProfiles*', hlcAdmin.getAllProfiles); router.get('/composer/admin/listAsAdmin*', hlcAdmin.listAsAdmin); router.get('/composer/admin/getRegistries*', hlcAdmin.getRegistries); + router.post('/composer/admin/createProfile*', hlcAdmin.createProfile); router.post('/composer/admin/deleteProfile*', hlcAdmin.deleteProfile); router.post('/composer/admin/deploy*', hlcAdmin.deploy); @@ -90,6 +93,7 @@ router.post('/composer/admin/checkCard*', hlcAdmin.checkCard); router.post('/composer/admin/createCard*', hlcAdmin.createCard); router.post('/composer/admin/issueIdentity*', hlcAdmin.issueIdentity); + // router requests specific to the Buyer router.get('/composer/client/getItemTable*', hlcClient.getItemTable); router.post('/composer/client/getMyOrders*', hlcClient.getMyOrders); diff --git a/Chapter06/favicon.ico b/Chapter06/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter06/favicon.ico and /dev/null differ diff --git a/Chapter06/index.js b/Chapter06/index.js index cb64e45..cf79cb7 100644 --- a/Chapter06/index.js +++ b/Chapter06/index.js @@ -14,25 +14,28 @@ /* * Zero to Blockchain */ -var express = require('express'); -var http = require('http'); -var https = require('https'); -var path = require('path'); -var fs = require('fs'); -var mime = require('mime'); -var bodyParser = require('body-parser'); -var cfenv = require('cfenv'); -var cookieParser = require('cookie-parser'); -var session = require('express-session'); +'use strict'; +const express = require('express'); +const http = require('http'); +const ws = require('websocket').server; +// const https = require('https'); +const path = require('path'); +const fs = require('fs'); +const mime = require('mime'); +const bodyParser = require('body-parser'); +const cfenv = require('cfenv'); -var vcapServices = require('vcap_services'); -var uuid = require('uuid'); -var env = require('./controller/envV2.json'); -var sessionSecret = env.sessionSecret; -var appEnv = cfenv.getAppEnv(); -var app = express(); -var busboy = require('connect-busboy'); +const cookieParser = require('cookie-parser'); +// const session = require('express-session'); + +// const vcapServices = require('vcap_services'); +// const uuid = require('uuid'); +const env = require('./controller/envV2.json'); +const sessionSecret = env.sessionSecret; +const appEnv = cfenv.getAppEnv(); +const app = express(); +const busboy = require('connect-busboy'); app.use(busboy()); // the session secret is a text string of arbitrary length which is @@ -49,7 +52,8 @@ app.use(cookieParser(sessionSecret)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); -app.set('appName', 'z2b-chapter05'); +app.set('appName', 'z2b-chapter12'); +process.title = 'Z2B-C12'; app.set('port', appEnv.port); app.set('views', path.join(__dirname + '/HTML')); @@ -59,15 +63,58 @@ app.use(express.static(__dirname + '/HTML')); app.use(bodyParser.json()); // Define your own router file in controller folder, export the router, add it into the index.js. -// app.use('/', require("./controller/yourOwnRouter")); -app.use('/', require("./controller/restapi/router")); +app.use('/', require('./controller/restapi/router')); -if (cfenv.getAppEnv().isLocal == true) - { var server = app.listen(app.get('port'), function() {console.log('Listening locally on port %d', server.address().port);}); } - else - { var server = app.listen(app.get('port'), function() {console.log('Listening remotely on port %d', server.address().port);}); } +let server = http.createServer(); +let clients = []; +app.locals.index=-1; +/** + * WebSocket server + */ +app.locals.wsServer = new ws({httpServer: server}); +app.locals.wsServer.on('request', function(request) +{ + // create a connection back to the requestor + app.locals.connection = request.accept(null, request.origin); + // we need to know client index to remove them on 'close' event + app.locals.index = clients.push(app.locals.connection) - 1; + // save the newly created connection. This is so that we can support many connections to many browsers simultaneously + console.log((new Date()) + ' Connection accepted.'); + app.locals.connection.on('message', function(message) + { let obj ={ime: (new Date()).getTime(),text: message.utf8Data}; + // broadcast message to all connected clients + let json = JSON.stringify({ type:'Message', data: obj }); + app.locals.processMessages(json); + }); + // user disconnected + app.locals.connection.on('close', function(_conn) { + console.log((new Date()) + ' Peer '+ app.locals.connection.socket._peername.address+':'+app.locals.connection.socket._peername.port+' disconnected with reason code: "'+_conn+'".'); + // remove user from the list of connected clients + // each browser connection has a unique address and socket combination + // When a browser session is disconnected, remove it from the array so we don't waste processing time sending messages to empty queues. + for (let each in clients) + {(function(_idx, _arr) + {if ((_arr[_idx].socket._peername.address === app.locals.connection.socket._peername.address) && (_arr[_idx].socket._peername.port === app.locals.connection.socket._peername.port)) + {clients.splice(_idx, 1);} + })(each, clients);} + }); +}); + +/** + * callable function to send messages over web socket + * @param {JSON} _jsonMsg - json formatted content to be sent as message data + */ +function processMessages (_jsonMsg) +{ + for (let i=0; i < clients.length; i++) {clients[i].send(JSON.stringify(_jsonMsg));} +} +// make the processMessages function available to all modules in this app. +app.locals.processMessages = processMessages; +// now set up the http server +server.on( 'request', app ); +server.listen(appEnv.port, function() {console.log('Listening locally on port %d', server.address().port);}); /** * load any file requested on the server * @param {express.req} req - the inbound request object from the client @@ -75,29 +122,17 @@ if (cfenv.getAppEnv().isLocal == true) * @function */ function loadSelectedFile(req, res) { - var uri = req.originalUrl; - var filename = __dirname + "/HTML" + uri; + let uri = req.originalUrl; + let filename = __dirname + '/HTML' + uri; fs.readFile(filename, function(err, data) { if (err) { console.log('Error loading ' + filename + ' error: ' + err); return res.status(500).send('Error loading ' + filename); } - var type = mime.lookup(filename); - res.setHeader('content-type', type); + let type = mime.lookup(filename); + res.setHeader('content-type', type); res.writeHead(200); res.end(data); }); } - -/** - * display using console.log the properties of each property in the inbound object - * @param {displayObjectProperties} _string - string name of object - * @param {displayObjectProperties} _object - the object to be parsed - * @utility - */ -function displayObjectValues (_string, _object) -{ - for (prop in _object){ - console.log(_string+prop+": "+(((typeof(_object[prop]) == 'object') || (typeof(_object[prop]) == 'function')) ? typeof(_object[prop]) : _object[prop]));} -} diff --git a/Chapter06/network/lib/sample.js b/Chapter06/network/lib/sample.js index b243bc9..cf20b90 100644 --- a/Chapter06/network/lib/sample.js +++ b/Chapter06/network/lib/sample.js @@ -104,7 +104,7 @@ function OrderFromSupplier(purchase) { * @transaction */ function RequestShipping(purchase) { - if (purchase.order.status == JSON.stringify(orderStatus.Ordered)) + if ((purchase.order.status == JSON.stringify(orderStatus.Ordered)) || (purchase.order.status == JSON.stringify(orderStatus.Backordered))) { purchase.order.shipper = purchase.shipper; purchase.order.requestShipment = new Date().toISOString(); @@ -159,11 +159,11 @@ function RequestPayment(purchase) { {purchase.order.status = JSON.stringify(orderStatus.PayRequest); purchase.order.financeCo = purchase.financeCo; purchase.order.paymentRequested = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -174,11 +174,11 @@ function AuthorizePayment(purchase) { if ((JSON.parse(purchase.order.status).text == orderStatus.PayRequest.text ) || (JSON.parse(purchase.order.status).text == orderStatus.Resolve.text )) {purchase.order.status = JSON.stringify(orderStatus.Authorize); purchase.order.approved = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -189,11 +189,11 @@ function Pay(purchase) { if (JSON.parse(purchase.order.status).text == orderStatus.Authorize.text ) {purchase.order.status = JSON.stringify(orderStatus.Paid); purchase.order.paid = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a dispute by the buyer diff --git a/Chapter07/Documentation/answers/composer/hlcClient_complete.js b/Chapter07/Documentation/answers/composer/hlcClient_complete.js index d484aa5..307708d 100644 --- a/Chapter07/Documentation/answers/composer/hlcClient_complete.js +++ b/Chapter07/Documentation/answers/composer/hlcClient_complete.js @@ -18,11 +18,12 @@ let fs = require('fs'); let path = require('path'); const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition; -// const config = require('../../../env.json'); +const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; let itemTable = null; const svc = require('./Z2B_Services'); const financeCoID = 'easymoney@easymoneyinc.com'; +let bRegistered = false; /** * get orders for buyer with ID = _id @@ -229,7 +230,7 @@ exports.orderAction = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(' retrying assetRegistry.update for: '+req.body.orderNo); - svc.loadTransaction(svc.m_connection, updateOrder, req.body.orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, updateOrder, req.body.orderNo, businessNetworkConnection); } else {console.log(req.body.orderNo+' submitTransaction to update status to '+req.body.action+' failed with text: ',error.message);} @@ -314,7 +315,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else {console.log(orderNo+' submitTransaction failed with text: ',error.message);} @@ -323,7 +324,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else { @@ -338,7 +339,97 @@ exports.addOrder = function (req, res, next) { }); }) .catch((error) => { - console.log(orderNo+' business network connection failed: text',error.message); + console.log(method + ' : '+orderNo+' business network connection failed: text',error.message); res.send({'result': 'failed', 'error':' order '+orderNo+' add failed on on business network connection '+error.message}); }); }; + +/** + * _monitor + * @param {WebSocket} _conn - web socket to use for member event posting + * @param {WebSocket} _f_conn - web sockect to use for FinanceCo event posting + * @param {Event} _event - the event just emitted + * + */ +function _monitor(locals, _event) +{ + let method = '_monitor'; + console.log(method+ ' _event received: '+_event.$type+' for Order: '+_event.orderID); + // create an event object and give it the event type, the orderID, the buyer id and the eventID + // send that event back to the requestor + // ========> Your Code Goes Here <========= + + // using switch/case logic, send events back to each participant who should be notified. + // for example, when a seller requests payment, they should be notified when the transaction has completed + // and the financeCo should be notified at the same time. + // so you would use the _conn connection to notify the seller and the + // _f_conn connection to notify the financeCo + + switch (_event.$type) + { + case 'Created': + break; + case 'Bought': + case 'PaymentRequested': + // ========> Your Code Goes Here <========= + break; + case 'Ordered': + case 'Cancelled': + case 'Backordered': + // ========> Your Code Goes Here <========= + break; + case 'ShipRequest': + case 'DeliveryStarted': + case 'DeliveryCompleted': + // ========> Your Code Goes Here <========= + break; + case 'DisputeOpened': + case 'Resolved': + case 'Refunded': + case 'Paid': + // ========> Your Code Goes Here <========= + break; + case 'PaymentAuthorized': + // ========> Your Code Goes Here <========= + break; + default: + break; + } + +} + +/** + * Register for all of the available Z2BEvents + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + * @returns {Object} - returns are via res.send +*/ +exports.init_z2bEvents = function (req, res, next) +{ + let method = 'init_z2bEvents'; + if (bRegistered) {res.send('Already Registered');} + else{ + bRegistered = true; +// svc.createAlertSocket(); + let businessNetworkConnection; + businessNetworkConnection = new BusinessNetworkConnection(); + businessNetworkConnection.setMaxListeners(50); + // + // v0.14 + // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // + // v0.15 + return businessNetworkConnection.connect(config.composer.adminCard) + .then(() => { + // using the businessNetworkConnection, start monitoring for events. + // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information + businessNetworkConnection.on('event', (event) => {_monitor(req.app.locals, event); }); + res.send('event registration complete'); + }).catch((error) => { + // if an error is encountered, log the error and send it back to the requestor + console.log(method+' business network connection failed'+error.message); + res.send(method+' business network connection failed'+error.message); + }); + } +}; diff --git a/Chapter07/Documentation/answers/js/z2b-seller_complete.js b/Chapter07/Documentation/answers/js/z2b-seller_complete.js index ecc7209..19072a8 100644 --- a/Chapter07/Documentation/answers/js/z2b-seller_complete.js +++ b/Chapter07/Documentation/answers/js/z2b-seller_complete.js @@ -16,36 +16,38 @@ 'use strict'; let sellerOrderDiv = 'sellerOrderDiv'; - +let s_alerts = []; +let s_notify = '#seller_notify'; +let s_count = '#seller_count'; +let s_id; /** * load the administration Seller Experience */ function loadSellerUX () { let toLoad = 'seller.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupSeller(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupSeller(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupSeller(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupSeller(page);}); } } /** * load the administration User Experience * @param {String} page - page to load - * @param {Integer} port - web socket port to use */ -function setupSeller(page, port) +function setupSeller(page) { $('#body').empty(); $('#body').append(page); + if (s_alerts.length == 0) + {$(s_notify).removeClass('on'); $(s_notify).addClass('off'); } + else {$(s_notify).removeClass('off'); $(s_notify).addClass('on'); } updatePage('seller'); - msgPort = port.port; - wsDisplay('seller_messages', msgPort); let _clear = $('#seller_clear'); let _list = $('#sellerOrderStatus'); let _orderDiv = $('#'+sellerOrderDiv); @@ -58,9 +60,15 @@ function setupSeller(page, port) $('#seller').append(s_string); $('#sellerCompany').empty(); $('#sellerCompany').append(sellers[0].companyName); - $('#seller').on('change', function() { + s_id = sellers[0].id; + z2bSubscribe('Seller', s_id); + // create a function to execute when the user selects a different provider + $('#seller').on('change', function() { $('#sellerCompany').empty(); _orderDiv.empty(); $('#seller_messages').empty(); $('#sellerCompany').append(findMember($('#seller').find(':selected').val(),sellers).companyName); + z2bUnSubscribe(s_id); + s_id = findMember($('#seller').find(':selected').text(),sellers).id; + z2bSubscribe('Seller', s_id); }); } /** @@ -151,7 +159,7 @@ function formatSellerOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    "+_curObj+""+_arr[_idx][_curObj]+"
    "+_curObj[0]+""+_curObj2+""+_arr2[_idx2][_curObj2[0]]+"
    '+_curObj+''+_arr[_idx][_curObj]+'
    '+_curObj[0]+''+_curObj2+''+_arr2[_idx2][_curObj2[0]]+'
    '; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+r_string+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.seller+findMember(_arr[_idx].seller.split('#')[1],sellers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+r_string+_button+''; _str+= '' for (let every in _arr[_idx].items) { @@ -286,18 +309,26 @@ function formatOrders(_target, _orders) // iterate through the page and make all of the different parts of the page active. // for (let each in _orders) - {(function(_idx, _arr) - { $('#b_btn_'+_idx).on('click', function () - { - let options = {}; - options.action = $('#b_action'+_idx).find(':selected').text(); - options.orderNo = $('#b_order'+_idx).text(); - options.participant = $('#buyer').val(); - if ((options.action === 'Dispute') || (options.action === 'Resolve')) {options.reason = $('#b_reason'+_idx).val();} - $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); - $.when($.post('/composer/client/orderAction', options)).done(function (_results) - { $('#buyer_messages').prepend(formatMessage(_results.result)); }); - }); - })(each, _orders) + {(function(_idx, _arr) + { $('#b_btn_'+_idx).on('click', function () + { + let options = {}; + options.action = $('#b_action'+_idx).find(':selected').text(); + options.orderNo = $('#b_order'+_idx).text(); + options.participant = $('#buyer').val(); + if ((options.action === 'Dispute') || (options.action === 'Resolve')) + {options.reason = $('#b_reason'+_idx).val();} + $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); + $.when($.post('/composer/client/orderAction', options)).done(function (_results) + { $('#buyer_messages').prepend(formatMessage(_results.result)); }); + }); + // use the notifyMe function to determine if this order is in the alert array. + // if it is, the highlight the $('#b_status'+_idx) html element by adding the 'highlight' class + if (notifyMe(b_alerts, _arr[_idx].id)) {$('#b_status'+_idx).addClass('highlight'); } + })(each, _orders); } + // reset the b_alerts array to a new array + b_alerts = new Array(); + // call the toggleAlerts function to reset the alert icon + toggleAlert($('#buyer_notify'), b_alerts, b_alerts.length); } \ No newline at end of file diff --git a/Chapter07/HTML/js/z2b-events.js b/Chapter07/HTML/js/z2b-events.js index 3da467d..282f3ea 100644 --- a/Chapter07/HTML/js/z2b-events.js +++ b/Chapter07/HTML/js/z2b-events.js @@ -16,6 +16,41 @@ 'use strict'; +let wsSocket; + +/** + * load the four initial user roles into a single page. + */ +function singleUX () +{ + let toLoad = 'singleUX.html'; + if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } + else{ + $.when($.get(toLoad)).done(function(_page) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } +} /** * load all of the members in the network for use in the different user experiences. This is a synchronous routine and is executed autormatically on web app start. * However, if this is a newly created network, then there are no members to retrieve and this will create four empty arrays @@ -33,20 +68,29 @@ function memberLoad () $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members; - p_string = _getMembers(providers); - shippers = _shippers[0].members; - sh_string = _getMembers(shippers); + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + }); } - +/** + * dropDummy() removes 'noop@dummy' from memberlist + * @param {String} _in - member id to ignore + */ +function dropDummy(_in) +{ + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} + return _a; +} /** * load all of the members in the network for use in the different user experiences. This routine is designed for use if the network has been newly deployed and the web app was * started before the autoLoad function was run on the newly deployed network (which, by default, is empty). - * @returns {Promise} - promise upon completino of loadding member objects. */ function deferredMemberLoad() { @@ -62,28 +106,178 @@ function deferredMemberLoad() $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members; - p_string = _getMembers(providers); - shippers = _shippers[0].members; - sh_string = _getMembers(shippers); - d_prompts.resolve(); + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + d_prompts.resolve(); }).fail(d_prompts.reject); return d_prompts.promise(); } /** * return an option list for use in an HTML '; return _str; +} +/** + * set up the server to listen for all events + */ +function goEventInitialize() +{ + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); +} + +/** + * @param {Event} _event - inbound Event + * @param {String} _id - subscriber target + * @param {String} _orderID - inbound order id + */ +function addNotification(_event, _id, _orderID) +{ + let method = 'addNotification'; + console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); + let type = getSubscriber(_id); + if (type === 'none') {return;} + switch(type) + { + case 'Buyer': + b_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(b_notify, b_alerts, b_count); + break; + case 'Seller': + s_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(s_notify, s_alerts, s_count); + break; + case 'Provider': + p_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(p_notify, p_alerts, p_count); + break; + case 'Shipper': + sh_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(sh_notify, sh_alerts, sh_count); + break; + case 'FinanceCo': + f_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(f_notify, f_alerts, f_count); + break; + default: + console.log(method+' default entered for: '+type); + break; + } +} +/** + * + * @param {jQuery} _target - jquery object to update + * @param {Array} _array - array of alerts for this member + * @param {jQuery} _count - jQuery object to hold alert count + */ +function toggleAlert(_target, _array, _count) +{ + if (_array.length < 1) + {$(_target).removeClass('on'); $(_target).addClass('off'); } + else {$(_count).empty(); $(_count).append(_array.length); + $(_target).removeClass('off'); $(_target).addClass('on'); } + +} +/** + * check to see if _id is subscribing + * @param {Integer} _id - member id to seek + * @returns {String} - type of member + */ +function getSubscriber(_id) +{ + let type = 'none'; + for (let each in subscribers){(function(_idx, _arr){if (_arr[_idx].id === _id){type=_arr[_idx].type;}})(each, subscribers);} + return(type); +} +/** + * subscribe to events + * @param {String} _type - member type + * @param {String} _id - member id + */ +function z2bSubscribe(_type, _id) +{ + subscribers.push({'type': _type, 'id': _id}); +} +/** + * Unsubscribe to events + * @param {String} _id - member id to remove + */ +function z2bUnSubscribe(_id) +{ + let _s1 = subscribers; + let _s2 = []; + for (let each in _s1) {(function(_idx, _arr){if (_arr[_idx] != _id){_s2.push(_arr[_idx]);}})(each, _s1);} + subscribers = _s2; +} +/** + * notifyMe + * @param {Array} _alerts - array of alerts + * @param {String} _id - orderID + * @returns {Boolean} - true if found, false if not found + */ +function notifyMe (_alerts, _id) +{ + let b_h = false; + for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} + return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter07/HTML/js/z2b-initiate.js b/Chapter07/HTML/js/z2b-initiate.js index bc5076a..7ba4493 100644 --- a/Chapter07/HTML/js/z2b-initiate.js +++ b/Chapter07/HTML/js/z2b-initiate.js @@ -20,7 +20,13 @@ let connectionProfileName = 'z2b-test-profile'; let networkFile = 'zerotoblockchain-network.bna'; let businessNetwork = 'zerotoblockchain-network'; -let buyers, sellers, providers, shippers; +let host_address = window.location.host; + +let buyers = new Array(); +let sellers= new Array(); +let providers= new Array(); +let shippers= new Array(); + let s_string, p_string, sh_string; let orderStatus = { @@ -53,4 +59,6 @@ function initPage () memberLoad(); // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring getChainEvents(); + // get the asynch port + wsConnect(); } diff --git a/Chapter07/HTML/js/z2b-utilities.js b/Chapter07/HTML/js/z2b-utilities.js index ae1637f..7f2c962 100644 --- a/Chapter07/HTML/js/z2b-utilities.js +++ b/Chapter07/HTML/js/z2b-utilities.js @@ -6,68 +6,72 @@ * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, + * distributed under the License is distributed on an "AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -// z2c-utilities.js - +// z2c-utilities.js +'use strict'; /** * creates a set of utilities inside the named space: z2c * All utilities are accessed as z2c.functionName() * @namespace - z2c */ -languages = {}, // getSupportedLanguages -selectedLanguage = {}, -language = "", -textLocations = {}, // getTextLocations -textPrompts = {}, // getSelectedPromots +let languages = {}, // getSupportedLanguages + selectedLanguage = {}, + language = '', + textLocations = {}, // getTextLocations + textPrompts = {}, // getSelectedPromots + subscribers = new Array(); // subscribers to business events /** * get the value associated with a cookie named in the input * Refer to this by {@link getCookieValue}. * @param {String} _name - the name of the cookie to find -* @namespace +* @returns {String} - cookie value +* @namespace */ function getCookieValue(_name) { - var name = _name+"="; - var cookie_array= document.cookie.split(";"); - for (each in cookie_array) - { var c = cookie_array[each].trim(); - if(c.indexOf(name) == 0) return(c.substring(name.length, c.length)); - } - return(""); + let name = _name+'='; + let cookie_array= document.cookie.split(';'); + for (let each in cookie_array) + { + let c = cookie_array[each].trim(); + if(c.indexOf(name) === 0) {return(c.substring(name.length, c.length));} + } + return(''); } /** * trims a string by removing all leading and trailing spaces * trims the final period, if it exists, from a string. * Refer to this by {@link trimStrip}. -* @param {String} _string String to be trimmed and stripped of trailing period -* @namespace +* @param {String} _string - String to be trimmed and stripped of trailing period +* @returns {String} - trimmed string +* @namespace */ function trimStrip(_string) { - var str = _string.trim(); - var len = str.length; - if(str.endsWith(".")) {str=str.substring(0,len-1);} - return(str); + let str = _string.trim(); + let len = str.length; + if(str.endsWith('.')) {str=str.substring(0,len-1);} + return(str); } /** * replaces text on an html page based on the anchors and text provided in a JSON textPrompts object * Refer to this by {@link updatePage}. * @param {String} _page - a string representing the name of the html page to be updated -* @namespace +* @namespace */ function updatePage(_page) { - for (each in textPrompts[_page]){(function(_idx, _array) - {$("#"+_idx).empty();$("#"+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} + for (let each in textPrompts[_page]){(function(_idx, _array) + {$('#'+_idx).empty();$('#'+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} } /** @@ -75,7 +79,8 @@ function updatePage(_page) * Refer to this by {@link getDisplaytext}. * @param {String} _page - string representing the name of the html page to be updated * @param {String} _item - string representing the html named item to be updated -* @namespace +* @returns {String} - text to be placed on web page +* @namespace */ function getDisplaytext(_page, _item) {return (textPrompts[_page][_item]);} @@ -85,54 +90,56 @@ function getDisplaytext(_page, _item) * Refer to this by {@link goMultiLingual}. * @param {String} _language - language to be used in this session * @param {String} _page - string representing html page to be updated in the selected language -* @namespace +* @namespace */ function goMultiLingual(_language, _page) { language = _language; - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - {languages = _res; - selectedLanguage = languages[_language]; - var options = {}; options.language = _language; - $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) - {textLocations = _locations; - textPrompts = JSON.parse(_prompts[0]); - updatePage(_page); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + {languages = _res; + selectedLanguage = languages[_language]; + let options = {}; options.language = _language; + $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) + {textLocations = _locations; + textPrompts = JSON.parse(_prompts[0]); + updatePage(_page); + }); + let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • '} + })(each, _res); + } + _choices.append(_str); }); - var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); } /** * get SupportedLanguages returns an html menu object with available languages * Refer to this by {@link getSupportedLanguages}. -* @namespace +* @namespace */ function getSupportedLanguages() { - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - { - languages = _res; console.log(_res); var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + { + languages = _res; console.log(_res); let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • ';} + })(each, _res); + } + _choices.append(_str); + }); } /** * returns a JSON object with the pages and objects which support text replacement * Refer to this by {@link getTextLocations}. -* @namespace +* @namespace */ function getTextLocationsfunction () {$.when($.get('/api/getTextLocations')).done(function(_res){textLocations = _res; console.log(_res); });} @@ -140,38 +147,39 @@ function getTextLocationsfunction () /** * returns a JSON object with the text to be used to update identified pages and objects * Refer to this by {@link getSelectedPrompts}. -* @param {String} _inbound -* @namespace +* @param {String} _inbound - page or object to receive updated text +* @namespace */ function getSelectedPrompts(_inbound) { selectedLanguage=languages[_inbound]; - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); } /** * retrieves the prompts for the requested language from the server * Refer to this by {@link qOnSelectedPrompts}. * @param {String} _inbound - string representing the requested language -* @namespace +* @returns {Promise} - returns promise when selected prompts have been retrieved from server +* @namespace */ function qOnSelectedPrompts(_inbound) { - var d_prompts = $.Deferred(); - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); + return d_prompts.promise(); } /** * function to display the properties of an object using console.log * Refer to this by {@link displayObjectProperties}. * @param {Object} _obj - the object whose properties are to be displayed -* @namespace +* @namespace */ function displayObjectProperties(_obj) { - for(var propt in _obj){ console.log("object property: "+propt ); } + for(let propt in _obj){ console.log('object property: '+propt ); } } /** @@ -179,12 +187,12 @@ function displayObjectProperties(_obj) * Refer to this by {@link displayObjectValues}. * @param {String} _string - an arbitrary string to preface the printing of the object property name and value. often used to display the name of the object being printed * @param {Object} _object - the object to be introspected -* @namespace +* @namespace */ function displayObjectValues(_string, _object) { - for (prop in _object){ - console.log(_string+prop+": "+(((typeof(_object[prop]) == 'object') || (typeof(_object[prop]) == 'function')) ? typeof(_object[prop]) : _object[prop])); + for (let prop in _object){ + console.log(_string+prop+': '+(((typeof(_object[prop]) === 'object') || (typeof(_object[prop]) === 'function')) ? typeof(_object[prop]) : _object[prop])); } } @@ -201,124 +209,126 @@ function displayObjectValues(_string, _object) */ String.prototype.format = function(i, safe, arg) { +/** + * the format function added to String.prototype + * @returns {String} - returns original string with {x} replaced by provided text + */ + function format() { + let str = this, len = arguments.length+1; - function format() { - var str = this, len = arguments.length+1; - - // For each {0} {1} {n...} replace with the argument in that position. If - // the argument is an object or an array it will be stringified to JSON. - for (i=0; i < len; arg = arguments[i++]) { - safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; - str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + // For each {0} {1} {n...} replace with the argument in that position. If + // the argument is an object or an array it will be stringified to JSON. + for (i=0; i < len; arg = arguments[i++]) { + safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; + str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + } + return str; } - return str; - } - // Save a reference of what may already exist under the property native. - // Allows for doing something like: if("".format.native) { /* use native */ } - format.native = String.prototype.format; - - // Replace the prototype property - return format; + // Save a reference of what may already exist under the property native. + // Allows for doing something like: if(''.format.native) { /* use native */ } + format.native = String.prototype.format; + // Replace the prototype property + return format; }(); /** * display the hyperledger apis as currently understood * Refer to this by {@link showAPIDocs}. - * + * */ function showAPIDocs() { - $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) - { - var _target = $("#body"); - _target.empty(); _target.append(_page[0]); - displayAPI(_res[0]); - }); + $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) + { + let _target = $('#body'); + _target.empty(); _target.append(_page[0]); + displayAPI(_res[0]); + }); } /** - * - * @param {JSON} _api + * + * @param {JSON} _api * Refer to this by {@link displayAPI}. - * + * */ function displayAPI(_api) { - var _exports = _api.hfcExports; - var _classes = _api.hfcClasses; - var _eTarget = $("#hfc_exports"); - var _cTarget = $("#hfc_classes"); - var _str = ""; - for (each in _exports) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - _str += ""; - })(each, _exports); - } - _eTarget.append(_str); - _str = ""; - for (each in _classes) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - for (every in _arr[_idx][_curObj[0]]){ - (function(_idx2, _arr2) - { - _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); - _str+= ""; - })(every, _arr[_idx][_curObj[0]]) - } - })(each, _classes); - } - _cTarget.append(_str); + let _exports = _api.hfcExports; + let _classes = _api.hfcClasses; + let _eTarget = $('#hfc_exports'); + let _cTarget = $('#hfc_classes'); + let _str = ''; + for (let each in _exports) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + _str += ''; + })(each, _exports); + } + _eTarget.append(_str); + _str = ''; + for (let each in _classes) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + for (let every in _arr[_idx][_curObj[0]]){ + (function(_idx2, _arr2) + { + let _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); + _str+= ''; + })(every, _arr[_idx][_curObj[0]]); + } + })(each, _classes); + } + _cTarget.append(_str); } /** * format messages for display + * @param {String} _msg - text to be enclosed in html message format + * @returns {String} - html formatted message */ function formatMessage(_msg) {return '

    '+_msg+'

    ';} + /** - * get the web socket port + * closes all accordians in this div + * @param {String} target - formatted jQuery string pointing to div with all accordians to collapse */ -function getPort () +function accOff(target) { - if (msgPort == null) - { $.when($.get('/setup/getPort')).done(function (port){console.log('port is: '+port.port); msgPort = port.port;});} + let thisElement = $(target); + let childNodes = thisElement.children(); + for (let each in childNodes) + {let node = '#'+childNodes[each].id; + if (node !== '#') + { + if($(node).hasClass('on')) {$(node).removeClass('on');} + $(node).addClass('off'); + } + } } + /** * toggle an accordian window + * @param {String} _parent - Div holding all accordians + * @param {String} _body - Div which only appears when accordian is expanded + * @param {HTMLDiv} _header - Div which appears when accordian is collapsed */ function accToggle(_parent, _body, _header) { - var parent = "#"+_parent; - var body="#"+_body; - var header = _header; - if ($(body).hasClass("on")) - {$(body).removeClass("on"); $(body).addClass("off"); - $(parent).removeClass("on"); $(parent).addClass("off"); - }else - { - accOff(parent); - $(body).removeClass("off"); $(body).addClass("on"); - $(parent).removeClass("off"); $(parent).addClass("on"); - } -} -/** - * - */ -function accOff(target) -{ - var thisElement = $(target); - var childNodes = thisElement.children(); - for (each in childNodes) - {var node = "#"+childNodes[each].id; - if (node != '#') - { - if($(node).hasClass("on")) {$(node).removeClass("on");} - $(node).addClass("off"); - } - } + let parent = '#'+_parent; + let body='#'+_body; + if ($(body).hasClass('on')) + { + $(body).removeClass('on'); $(body).addClass('off'); + $(parent).removeClass('on'); $(parent).addClass('off'); + }else + { + accOff(parent); + $(body).removeClass('off'); $(body).addClass('on'); + $(parent).removeClass('off'); $(parent).addClass('on'); + } } diff --git a/Chapter07/controller/restapi/features/composer/Z2B_Services.js b/Chapter07/controller/restapi/features/composer/Z2B_Services.js index 21dbb85..c4f8aa4 100644 --- a/Chapter07/controller/restapi/features/composer/Z2B_Services.js +++ b/Chapter07/controller/restapi/features/composer/Z2B_Services.js @@ -13,16 +13,18 @@ */ 'use strict'; -var fs = require('fs'); -var path = require('path'); +let fs = require('fs'); +let path = require('path'); const sleep = require('sleep'); -const ws = require('websocket'); -const http = require('http'); +// const ws = require('websocket'); +// const http = require('http'); +// const url = require('url'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); const appEnv = cfenv.getAppEnv(); +const util = require('./Z2B_Utilities'); app.set('port', appEnv.port); @@ -37,7 +39,7 @@ app.set('port', appEnv.port); * @class * @memberof module:Z2Blockchain */ -var Z2Blockchain = { +let Z2Blockchain = { /** * create an empty order. This is used by any server side routine that needs to create an new @@ -105,8 +107,8 @@ var Z2Blockchain = { /** * update item quantity. used by the autoLoad process. * @param {item_number} _itemNo - item number to find - * @param {vendor_array} _itemArray - item array from order * @param {item_number} _qty - quantity to change * @utility + * @param {vendor_array} _itemArray - item array from order */ setItem: function (_itemNo, _qty, _itemArray) { @@ -115,46 +117,78 @@ var Z2Blockchain = { }, /** * supplemental routine to resubmit orders when MVCC_READ_CONFLICT encountered + * @param {object} _con - web socket connection * @param {transaction} _item - transaction to process * @param {order_object} _id - order id - * @param {bnc} businessNetworkConnection - already created business network connection + * @param {BusinessNetworkConnection} businessNetworkConnection - already created business network connection + * @returns {promise} promise */ loadTransaction: function (_con, _item, _id, businessNetworkConnection) { + let method = 'loadTransaction'; return businessNetworkConnection.submitTransaction(_item) .then(() => { - console.log('loadTransaction: order '+_id+' successfully added'); - _con.sendUTF('loadTransaction: order '+_id+' successfully added'); + console.log(method+': order '+_id+' successfully added '); + this.send(_con, 'Message', 'Order '+_id+' successfully added'); }) .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) + if (error.message.search('MVCC_READ_CONFLICT') !== -1) {sleep.sleep(5); - console.log(_id+" loadTransaction retrying submit transaction for: "+_id); - this.loadTransaction(_con,_item, _id, businessNetworkConnection); + console.log(_id+' loadTransaction retrying submit transaction for: '+_id); + this.loadTransaction(_con, _item, _id, businessNetworkConnection); } }); }, /** * add an order to a registry. This adds an Asset and does not execute a transaction - * @param {order_object} _order - order_object to process - * @param {assetRegistry} _registry - registry into which asset (order) should be placed + * @param {order_object} _con - websocket + * @param {assetRegistry} _order - order_object to process + * @param {networkTransaction} _registry - registry into which asset (order) should be placed * @param {networkTransaction} _createNew - transaction to be processed after order successfully added - * @param {businessNetworkConnection} _bnc - business network connection to use */ - addOrder: function (_con, _order, _registry, _createNew, _bnc) - { - return _registry.add(_order) - .then(() => { - this.loadTransaction(_con,_createNew, _order.orderNumber, _bnc); - }) - .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) - {console.log(_order.orderNumber+" addOrder retrying assetRegistry.add for: "+_order.orderNumber); - this.addOrder(_con,_order, _registry, _createNew, _bnc); - } - else {console.log('error with assetRegistry.add', error)} - }); + * @param {businessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +addOrder: function (_con, _order, _registry, _createNew, _bnc) +{ + let method = 'addOrder'; + return _registry.add(_order) + .then(() => { + this.loadTransaction(_con, _createNew, _order.orderNumber, _bnc); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(_order.orderNumber+' addOrder retrying assetRegistry.add for: '+_order.orderNumber); + this.addOrder(_con, _order, _registry, _createNew, _bnc); + } + else {console.log(method+' error with assetRegistry.add', error);} + }); }, +/** + * repeats the bind identity request + * @param {WebSocket} _con - order_object to process + * @param {String} _id - registry into which asset (order) should be placed + * @param {String} _cert - transaction to be processed after order successfully added + * @param {BusinessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +bindIdentity: function (_con, _id, _cert, _bnc) +{ + let method = 'bindIdentity'; + console.log(method+' retrying bindIdentity for: '+_id); + return _bnc.bindIdentity(_id, _cert) + .then(() => { + console.log(method+' Succeeded for: '+_id); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(' bindIdentity retrying _bnc.bindIdentity(_id, _cert) for: '+_id); + this.bindIdentity(_con, _id, _cert, _bnc); + } + else {console.log(method+' error with _bnc.bindIdentity(_id, _cert) for: '+_id+' with error: ', error);} + }); +}, + /** * saves the member table with ids and secrets * @param {array} _table - array of JSON objects to save to file @@ -166,23 +200,26 @@ var Z2Blockchain = { let _mem = '{"members": ['; for (let each in _table) {(function(_idx, _arr) - {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table)} + {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table);} _mem += ']}'; fs.writeFileSync(newFile, _mem, options); }, /** * saves the item table * @param {array} _table - array of JSON objects to save to file + * @param {JSON} _table - data to be saved */ - saveItemTable: function (_table) - { - let options = { flag : 'w' }; - let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); - let _mem = '{"items": ['; - for (let each in _table) - {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table)} - _mem += ']}'; - fs.writeFileSync(newFile, _mem, options); - }, +saveItemTable: function (_table) +{ + console.log('_table: ', _table); + let options = { flag : 'w' }; + let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); + let _mem = '{"items": ['; + for (let each in _table) + {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table);} + _mem += ']}'; + console.log('_mem: ', _mem); + fs.writeFileSync(newFile, _mem, options); +}, /** * update an empty order with 4 items. update the amount field based on the sum of the line items * @param {addItems} _inbound - Order created with factory.newResource(NS, 'Order',.orderNumber) @@ -205,7 +242,7 @@ var Z2Blockchain = { _arr[_idx].extendedPrice = _item.unitPrice*_arr[_idx].quantity; _amount += _arr[_idx].extendedPrice; _items.push(JSON.stringify(_arr[_idx])); - })(each, _inbound.items)} + })(each, _inbound.items);} return ({'items': _items, 'amount': _amount}); }, /** @@ -213,22 +250,23 @@ var Z2Blockchain = { * was not initially working. This function is no longer in use. * @param {Order} _order - the inbound Order item retrieved from a registry * @return JSON object order elements + * @return {Order} JSON object order elements * @function */ - getOrderData: function (_order) - { - let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', - 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; - var _obj = {}; - for (let each in orderElements){(function(_idx, _arr) - { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements)} - _obj.buyer = _order.buyer.$identifier; - _obj.seller = _order.seller.$identifier; - _obj.provider = _order.seller.$provider; - _obj.shipper = _order.seller.$shipper; - _obj.financeCo = _order.seller.$financeCo; - return (_obj); - }, +getOrderData: function (_order) +{ + let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', + 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; + let _obj = {}; + for (let each in orderElements){(function(_idx, _arr) + { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements);} + _obj.buyer = _order.buyer.$identifier; + _obj.seller = _order.seller.$identifier; + _obj.provider = _order.seller.$provider; + _obj.shipper = _order.seller.$shipper; + _obj.financeCo = _order.seller.$financeCo; + return (_obj); +}, /** * JSON object of available order status types and codes. This is used by nodejs @@ -252,67 +290,15 @@ var Z2Blockchain = { Refunded: {code: 13, text: 'Order Refunded'} }, /** - * the user experience is enhanced if the browser can be notified of aysnchronous events. - * the createMessateSockt function creates a web socket service to which the browser can - * attach. - * @param {integer} _port - port number to use for this socket connection - * @returns {websocket} - web socket connection to be used on the server side. - */ - m_connection: null, - m_socketAddr: null, - m_socket: null, - createMessageSocket: function (_port) - { - var port = (typeof(_port) == 'undefined' || _port == null) ? app.get('port')+1 : _port - if (this.m_socket == null) - { - this.m_socketAddr = port; - this.m_socket= new ws.server({httpServer: http.createServer().listen(this.m_socketAddr)}); - var _this = this; - this.m_socket.on('request', function(request) - { - _this.m_connection = request.accept(null, request.origin); - _this.m_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.m_connection.sendUTF('connected'); - _this.m_connection.on('close', function(m_connection) {console.log('m_connection closed'); }); - }); - }); - } - return {conn: this.m_connection, socket: this.m_socketAddr}; - }, -/** - * the cs_connection is used to display blockchain information to the web browser over - * a sepaarate port from the user experience socket. - * @returns {websocket} - web socket connection to be used on the server side. + * New code to support sending messages to socket clients + * @param {Object} _locals - shared variables and functions from index.js + * @param {String} type - type of event message to put on channel + * @param {Event} event - event message */ - - cs_connection: null, - cs_socketAddr: null, - cs_socket: null, - createChainSocket: function () - { - var port = app.get('port')+2; - if (this.cs_socket == null) - { - this.cs_socketAddr = port; - this.cs_socket= new ws.server({httpServer: http.createServer().listen(this.cs_socketAddr)}); - var _this = this; - this.cs_socket.on('request', function(request) - { - _this.cs_connection = request.accept(null, request.origin); - _this.cs_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.cs_connection.sendUTF('connected'); - _this.cs_connection.on('close', function(cs_connection) {console.log('cs_connection closed'); }); - }); - }); - } - return {conn: this.cs_connection, socket: this.cs_socketAddr}; - } - +send: function (_locals, type, event) +{ + _locals.processMessages({'type': type, 'data': event} ); } +}; module.exports = Z2Blockchain; \ No newline at end of file diff --git a/Chapter07/controller/restapi/features/composer/autoLoad.js b/Chapter07/controller/restapi/features/composer/autoLoad.js index ce3d81b..da256aa 100644 --- a/Chapter07/controller/restapi/features/composer/autoLoad.js +++ b/Chapter07/controller/restapi/features/composer/autoLoad.js @@ -34,32 +34,13 @@ const financeCoID = 'easymoney@easymoneyinc.com'; const svc = require('./Z2B_Services'); const config = require('../../../env.json'); + /** * itemTable and memberTable are used by the server to reduce load time requests * for member secrets and item information */ let itemTable = new Array(); let memberTable = new Array(); -let socketAddr; - - - - - -/** - * getPort is used to return the port number for socket interactions so that - * the browser can receive asynchronous notifications of work in process. - * This helps the user understand the current status of the auto load process. - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * - * @function - */ -exports.getPort = function(req, res, next) { - let _conn = svc.createMessageSocket(); - res.send({'port': _conn.socket}); -}; /** * autoLoad reads the memberList.json file from the Startup folder and adds members, @@ -78,9 +59,9 @@ exports.autoLoad = function(req, res, next) { // connect to the network let businessNetworkConnection; let factory; let participant; - svc.createMessageSocket(); - socketAddr = svc.m_socketAddr; - let adminConnection = new AdminConnection(); +// svc.createMessageSocket(); +// socketAddr = svc.m_socketAddr; +let adminConnection = new AdminConnection(); // connection prior to V0.15 // adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW) // connection in v0.15 @@ -110,7 +91,7 @@ exports.autoLoad = function(req, res, next) { return participantRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { participant = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); @@ -118,7 +99,7 @@ exports.autoLoad = function(req, res, next) { participantRegistry.add(participant) .then(() => { console.log('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); - svc.m_connection.sendUTF('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); + svc.send(req.app.locals, 'Message', '['+_idx+'] '+_arr[_idx].companyName+' successfully added'); }) .then(() => { // an identity is required before a member can take action in the network. @@ -144,7 +125,9 @@ exports.autoLoad = function(req, res, next) { config.connectionProfile.keyValStore = _home+config.connectionProfile.keyValStore; let tempCard = new hlc_idCard(_meta, config.connectionProfile); return adminConnection.importCard(result.userID, tempCard) - .then ((_res) => { if (_res) {console.log('card updated');} else {console.log('card imported');} }) + .then ((_res) => { + if (_res) {console.log('card updated');} else {console.log('card imported');} + }) .catch((error) => { console.error('adminConnection.importCard failed. ',error.message); }); @@ -172,7 +155,7 @@ exports.autoLoad = function(req, res, next) { return assetRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { // first, an Order Object is created @@ -186,8 +169,8 @@ exports.autoLoad = function(req, res, next) { const createNew = factory.newTransaction(config.composer.NS, 'CreateOrder'); order.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); order.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); - order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummy'); - order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummy'); + order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummyProvider'); + order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummyShipper'); order.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.order = factory.newRelationship(config.composer.NS, 'Order', order.$identifier); @@ -199,7 +182,7 @@ exports.autoLoad = function(req, res, next) { .then(() => { // then a createOrder transaction is processed which uses the chaincode // establish the order with it's initial transaction state. - svc.loadTransaction(svc.m_connection, createNew, order.orderNumber, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, order.orderNumber, businessNetworkConnection); }) .catch((error) => { // in the development environment, because of how timing is set up, it is normal to @@ -207,8 +190,8 @@ exports.autoLoad = function(req, res, next) { // logical transaction error. if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log('AL: '+_arr[_idx].id+' retrying assetRegistry.add for: '+_arr[_idx].id); - svc.addOrder(svc.m_connection, order, assetRegistry, createNew, businessNetworkConnection); - } + svc.addOrder(req.app.locals, order, assetRegistry, createNew, businessNetworkConnection); + } else {console.log('error with assetRegistry.add', error.message);} }); }); @@ -220,7 +203,7 @@ exports.autoLoad = function(req, res, next) { .catch((error) => {console.log('error with business network Connect', error.message);}); }) .catch((error) => {console.log('error with adminConnect', error.message);}); - res.send({'port': socketAddr}); + res.send({'result': 'Success'}); }; /** diff --git a/Chapter07/controller/restapi/features/composer/hlcAdmin.js b/Chapter07/controller/restapi/features/composer/hlcAdmin.js index 8e9e8b9..46b188c 100644 --- a/Chapter07/controller/restapi/features/composer/hlcAdmin.js +++ b/Chapter07/controller/restapi/features/composer/hlcAdmin.js @@ -24,8 +24,7 @@ const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefi const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; -// const svc = require('./Z2B_Services'); -// const mod = 'hlcAdmin.js'; + /** * display the admin and network info diff --git a/Chapter07/controller/restapi/features/composer/queryBlockChain.js b/Chapter07/controller/restapi/features/composer/queryBlockChain.js index 9b6a396..75b67d3 100644 --- a/Chapter07/controller/restapi/features/composer/queryBlockChain.js +++ b/Chapter07/controller/restapi/features/composer/queryBlockChain.js @@ -12,8 +12,9 @@ * limitations under the License. */ -var path = require('path'); -var fs = require('fs'); +'use strict'; +let path = require('path'); +let fs = require('fs'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); @@ -24,10 +25,10 @@ const hfc = require('fabric-client'); const hfcEH = require('fabric-client/lib/EventHub'); const svc = require('./Z2B_Services'); -const util = require('./Z2B_Utilities'); -const financeCoID = 'easymoney@easymoneyinc.com'; +// const util = require('./Z2B_Utilities'); +// const financeCoID = 'easymoney@easymoneyinc.com'; const config = require('../../../env.json'); -var chainEvents = false; +let chainEvents = false; @@ -38,11 +39,13 @@ var chainEvents = false; * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainInfo = function(req, res, next) { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); - console.log(wallet_path); +exports.getChainInfo = function(req, res, next) +{ + let method='getChainInfo'; + let HOST_NAME = req.headers.host; + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); Promise.resolve().then(() => { // // As of 9/28/2017 there is a known and unresolved bug in HyperLedger Fabric @@ -61,29 +64,43 @@ exports.getChainInfo = function(req, res, next) { // change PeerAdmin in following line to adminID return client.getUserContext(config.composer.PeerAdmin, true);}) .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + if (user === null || user === undefined || user.isEnrolled() === false) + { console.error('User not defined, or not enrolled - error');} + if (HOST_NAME.slice(0,9) === 'localhost') + { + console.log(method+" running locally"); channel = client.newChannel(config.fabric.channelName); channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - }) + }else + { + console.log(method+" running remotely, not supported in Chapter 12"); + } + }) .then(() => { return channel.queryInfo() .then((blockchainInfo) => { if (blockchainInfo) { - res.send({"result": "success", "currentHash": blockchainInfo.currentBlockHash.toString("hex"), blockchain: blockchainInfo}); + res.send({'result': 'success', 'currentHash': blockchainInfo.currentBlockHash.toString('hex'), blockchain: blockchainInfo}); } else { console.log('response_payload is null'); - res.send({"result": "uncertain", "message": 'response_payload is null'}); + res.send({'result': 'uncertain', 'message': 'response_payload is null'}); } }) .catch((_err) => { - console.log("queryInfo failed with _err = ", _err); - res.send({"result": "failed", "message": _err.message}); - }); + console.log('queryInfo failed with _err = ', _err); + res.send({'result': 'failed', 'message': _err.message}); + }); }); - }); -} + }); +}; /** * get chain events @@ -92,37 +109,55 @@ exports.getChainInfo = function(req, res, next) { * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainEvents = function(req, res, next) { +exports.getChainEvents = function(req, res, next) +{ + let method = 'getChainEvents'; + let HOST_NAME = req.headers.host; if (chainEvents) {res.send({'port': svc.cs_socketAddr});} else { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); + Promise.resolve().then(() => { client = new hfc(); return hfc.newDefaultKeyValueStore({ path: wallet_path }) .then((wallet) => { client.setStateStore(wallet); // change PeerAdmin in following line to adminID - return client.getUserContext(config.composer.PeerAdmin, true);}) - .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} - channel = client.newChannel(config.fabric.channelName); - channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); - channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - // change Admin in following line to admin - var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); - var adminPEM = fs.readFileSync(pemPath).toString(); - var bcEvents = new hfcEH(client); - bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + return client.getUserContext(config.composer.PeerAdmin, true); + }) + .then((user) => { + if (user === null || user === undefined || user.isEnrolled() === false) + {console.error(method+': User not defined, or not enrolled - error');} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + // get the channel name + channel = client.newChannel(config.fabric.channelName); + //get the request URL for the Peer0 container + channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); + // get the orderer URL + channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); + // change Admin in following line to admin + var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); + var adminPEM = fs.readFileSync(pemPath).toString(); + var bcEvents = new hfcEH(client); + bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + bcEvents.registerBlockEvent( + function(event){svc.send(req.app.locals, 'BlockChain', event);}, + function(error){console.log(method+': registerBlockEvent error: ', error);} + ); bcEvents.connect(); - svc.createChainSocket(); - bcEvents.registerBlockEvent(function(event) {svc.cs_connection.sendUTF(JSON.stringify(event));}); - chainEvents = true; - res.send({'port': svc.cs_socketAddr}); - }) - }); - } -} + chainEvents = true; + res.send({'port': svc.cs_socketAddr}); + }) + .catch((err) => { console.log(method+': getUserContext failed: ',err);}); + }); + } +}; diff --git a/Chapter07/controller/restapi/router.js b/Chapter07/controller/restapi/router.js index 6fa15bd..14883e7 100644 --- a/Chapter07/controller/restapi/router.js +++ b/Chapter07/controller/restapi/router.js @@ -25,13 +25,15 @@ let hlcAdmin = require('./features/composer/hlcAdmin'); let hlcClient = require('./features/composer/hlcClient'); let setup = require('./features/composer/autoLoad'); let hlcFabric = require('./features/composer/queryBlockChain'); -router.post('/setup/autoLoad*', setup.autoLoad); -router.get('/setup/getPort*', setup.getPort); + router.get('/fabric/getChainInfo', hlcFabric.getChainInfo); router.get('/fabric/getChainEvents', hlcFabric.getChainEvents); router.get('/fabric/getHistory', hlcAdmin.getHistory); +router.post('/setup/autoLoad*', setup.autoLoad); +router.get('/composer/client/initEventRegistry*', hlcClient.init_z2bEvents); + module.exports = router; let count = 0; /** @@ -71,6 +73,7 @@ router.get('/composer/admin/getAllProfiles*', hlcAdmin.getAllProfiles); router.get('/composer/admin/listAsAdmin*', hlcAdmin.listAsAdmin); router.get('/composer/admin/getRegistries*', hlcAdmin.getRegistries); + router.post('/composer/admin/createProfile*', hlcAdmin.createProfile); router.post('/composer/admin/deleteProfile*', hlcAdmin.deleteProfile); router.post('/composer/admin/deploy*', hlcAdmin.deploy); @@ -90,6 +93,7 @@ router.post('/composer/admin/checkCard*', hlcAdmin.checkCard); router.post('/composer/admin/createCard*', hlcAdmin.createCard); router.post('/composer/admin/issueIdentity*', hlcAdmin.issueIdentity); + // router requests specific to the Buyer router.get('/composer/client/getItemTable*', hlcClient.getItemTable); router.post('/composer/client/getMyOrders*', hlcClient.getMyOrders); diff --git a/Chapter07/favicon.ico b/Chapter07/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter07/favicon.ico and /dev/null differ diff --git a/Chapter07/index.js b/Chapter07/index.js index 70319d6..cf79cb7 100644 --- a/Chapter07/index.js +++ b/Chapter07/index.js @@ -14,25 +14,28 @@ /* * Zero to Blockchain */ -var express = require('express'); -var http = require('http'); -var https = require('https'); -var path = require('path'); -var fs = require('fs'); -var mime = require('mime'); -var bodyParser = require('body-parser'); -var cfenv = require('cfenv'); -var cookieParser = require('cookie-parser'); -var session = require('express-session'); +'use strict'; +const express = require('express'); +const http = require('http'); +const ws = require('websocket').server; +// const https = require('https'); +const path = require('path'); +const fs = require('fs'); +const mime = require('mime'); +const bodyParser = require('body-parser'); +const cfenv = require('cfenv'); -var vcapServices = require('vcap_services'); -var uuid = require('uuid'); -var env = require('./controller/envV2.json'); -var sessionSecret = env.sessionSecret; -var appEnv = cfenv.getAppEnv(); -var app = express(); -var busboy = require('connect-busboy'); +const cookieParser = require('cookie-parser'); +// const session = require('express-session'); + +// const vcapServices = require('vcap_services'); +// const uuid = require('uuid'); +const env = require('./controller/envV2.json'); +const sessionSecret = env.sessionSecret; +const appEnv = cfenv.getAppEnv(); +const app = express(); +const busboy = require('connect-busboy'); app.use(busboy()); // the session secret is a text string of arbitrary length which is @@ -49,7 +52,8 @@ app.use(cookieParser(sessionSecret)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); -app.set('appName', 'z2b-chapter07'); +app.set('appName', 'z2b-chapter12'); +process.title = 'Z2B-C12'; app.set('port', appEnv.port); app.set('views', path.join(__dirname + '/HTML')); @@ -59,14 +63,58 @@ app.use(express.static(__dirname + '/HTML')); app.use(bodyParser.json()); // Define your own router file in controller folder, export the router, add it into the index.js. -// app.use('/', require("./controller/yourOwnRouter")); -app.use('/', require("./controller/restapi/router")); +app.use('/', require('./controller/restapi/router')); + +let server = http.createServer(); +let clients = []; +app.locals.index=-1; +/** + * WebSocket server + */ +app.locals.wsServer = new ws({httpServer: server}); +app.locals.wsServer.on('request', function(request) +{ + // create a connection back to the requestor + app.locals.connection = request.accept(null, request.origin); + // we need to know client index to remove them on 'close' event + app.locals.index = clients.push(app.locals.connection) - 1; + // save the newly created connection. This is so that we can support many connections to many browsers simultaneously + console.log((new Date()) + ' Connection accepted.'); + app.locals.connection.on('message', function(message) + { let obj ={ime: (new Date()).getTime(),text: message.utf8Data}; + // broadcast message to all connected clients + let json = JSON.stringify({ type:'Message', data: obj }); + app.locals.processMessages(json); + }); + + // user disconnected + app.locals.connection.on('close', function(_conn) { + console.log((new Date()) + ' Peer '+ app.locals.connection.socket._peername.address+':'+app.locals.connection.socket._peername.port+' disconnected with reason code: "'+_conn+'".'); + // remove user from the list of connected clients + // each browser connection has a unique address and socket combination + // When a browser session is disconnected, remove it from the array so we don't waste processing time sending messages to empty queues. + for (let each in clients) + {(function(_idx, _arr) + {if ((_arr[_idx].socket._peername.address === app.locals.connection.socket._peername.address) && (_arr[_idx].socket._peername.port === app.locals.connection.socket._peername.port)) + {clients.splice(_idx, 1);} + })(each, clients);} + }); +}); -if (cfenv.getAppEnv().isLocal == true) - { var server = app.listen(app.get('port'), function() {console.log('Listening locally on port %d', server.address().port);}); } - else - { var server = app.listen(app.get('port'), function() {console.log('Listening remotely on port %d', server.address().port);}); } +/** + * callable function to send messages over web socket + * @param {JSON} _jsonMsg - json formatted content to be sent as message data + */ +function processMessages (_jsonMsg) +{ + for (let i=0; i < clients.length; i++) {clients[i].send(JSON.stringify(_jsonMsg));} +} +// make the processMessages function available to all modules in this app. +app.locals.processMessages = processMessages; +// now set up the http server +server.on( 'request', app ); +server.listen(appEnv.port, function() {console.log('Listening locally on port %d', server.address().port);}); /** * load any file requested on the server * @param {express.req} req - the inbound request object from the client @@ -74,16 +122,16 @@ if (cfenv.getAppEnv().isLocal == true) * @function */ function loadSelectedFile(req, res) { - var uri = req.originalUrl; - var filename = __dirname + "/HTML" + uri; + let uri = req.originalUrl; + let filename = __dirname + '/HTML' + uri; fs.readFile(filename, function(err, data) { if (err) { console.log('Error loading ' + filename + ' error: ' + err); return res.status(500).send('Error loading ' + filename); } - var type = mime.lookup(filename); - res.setHeader('content-type', type); + let type = mime.lookup(filename); + res.setHeader('content-type', type); res.writeHead(200); res.end(data); }); diff --git a/Chapter07/network/lib/sample.js b/Chapter07/network/lib/sample.js index b243bc9..cf20b90 100644 --- a/Chapter07/network/lib/sample.js +++ b/Chapter07/network/lib/sample.js @@ -104,7 +104,7 @@ function OrderFromSupplier(purchase) { * @transaction */ function RequestShipping(purchase) { - if (purchase.order.status == JSON.stringify(orderStatus.Ordered)) + if ((purchase.order.status == JSON.stringify(orderStatus.Ordered)) || (purchase.order.status == JSON.stringify(orderStatus.Backordered))) { purchase.order.shipper = purchase.shipper; purchase.order.requestShipment = new Date().toISOString(); @@ -159,11 +159,11 @@ function RequestPayment(purchase) { {purchase.order.status = JSON.stringify(orderStatus.PayRequest); purchase.order.financeCo = purchase.financeCo; purchase.order.paymentRequested = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -174,11 +174,11 @@ function AuthorizePayment(purchase) { if ((JSON.parse(purchase.order.status).text == orderStatus.PayRequest.text ) || (JSON.parse(purchase.order.status).text == orderStatus.Resolve.text )) {purchase.order.status = JSON.stringify(orderStatus.Authorize); purchase.order.approved = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -189,11 +189,11 @@ function Pay(purchase) { if (JSON.parse(purchase.order.status).text == orderStatus.Authorize.text ) {purchase.order.status = JSON.stringify(orderStatus.Paid); purchase.order.paid = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a dispute by the buyer diff --git a/Chapter08/Documentation/answers/composer/hlcClient_complete.js b/Chapter08/Documentation/answers/composer/hlcClient_complete.js index f43ff92..1998295 100644 --- a/Chapter08/Documentation/answers/composer/hlcClient_complete.js +++ b/Chapter08/Documentation/answers/composer/hlcClient_complete.js @@ -18,11 +18,12 @@ let fs = require('fs'); let path = require('path'); const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition; -// const config = require('../../../env.json'); +const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; let itemTable = null; const svc = require('./Z2B_Services'); const financeCoID = 'easymoney@easymoneyinc.com'; +let bRegistered = false; /** * get orders for buyer with ID = _id @@ -236,7 +237,7 @@ exports.orderAction = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(' retrying assetRegistry.update for: '+req.body.orderNo); - svc.loadTransaction(svc.m_connection, updateOrder, req.body.orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, updateOrder, req.body.orderNo, businessNetworkConnection); } else {console.log(req.body.orderNo+' submitTransaction to update status to '+req.body.action+' failed with text: ',error.message);} @@ -321,7 +322,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else {console.log(orderNo+' submitTransaction failed with text: ',error.message);} @@ -330,7 +331,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else { @@ -345,7 +346,97 @@ exports.addOrder = function (req, res, next) { }); }) .catch((error) => { - console.log(orderNo+' business network connection failed: text',error.message); + console.log(method + ' : '+orderNo+' business network connection failed: text',error.message); res.send({'result': 'failed', 'error':' order '+orderNo+' add failed on on business network connection '+error.message}); }); }; + +/** + * _monitor + * @param {WebSocket} _conn - web socket to use for member event posting + * @param {WebSocket} _f_conn - web sockect to use for FinanceCo event posting + * @param {Event} _event - the event just emitted + * + */ +function _monitor(locals, _event) +{ + let method = '_monitor'; + console.log(method+ ' _event received: '+_event.$type+' for Order: '+_event.orderID); + // create an event object and give it the event type, the orderID, the buyer id and the eventID + // send that event back to the requestor + // ========> Your Code Goes Here <========= + + // using switch/case logic, send events back to each participant who should be notified. + // for example, when a seller requests payment, they should be notified when the transaction has completed + // and the financeCo should be notified at the same time. + // so you would use the _conn connection to notify the seller and the + // _f_conn connection to notify the financeCo + + switch (_event.$type) + { + case 'Created': + break; + case 'Bought': + case 'PaymentRequested': + // ========> Your Code Goes Here <========= + break; + case 'Ordered': + case 'Cancelled': + case 'Backordered': + // ========> Your Code Goes Here <========= + break; + case 'ShipRequest': + case 'DeliveryStarted': + case 'DeliveryCompleted': + // ========> Your Code Goes Here <========= + break; + case 'DisputeOpened': + case 'Resolved': + case 'Refunded': + case 'Paid': + // ========> Your Code Goes Here <========= + break; + case 'PaymentAuthorized': + // ========> Your Code Goes Here <========= + break; + default: + break; + } + +} + +/** + * Register for all of the available Z2BEvents + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + * @returns {Object} - returns are via res.send +*/ +exports.init_z2bEvents = function (req, res, next) +{ + let method = 'init_z2bEvents'; + if (bRegistered) {res.send('Already Registered');} + else{ + bRegistered = true; +// svc.createAlertSocket(); + let businessNetworkConnection; + businessNetworkConnection = new BusinessNetworkConnection(); + businessNetworkConnection.setMaxListeners(50); + // + // v0.14 + // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // + // v0.15 + return businessNetworkConnection.connect(config.composer.adminCard) + .then(() => { + // using the businessNetworkConnection, start monitoring for events. + // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information + businessNetworkConnection.on('event', (event) => {_monitor(req.app.locals, event); }); + res.send('event registration complete'); + }).catch((error) => { + // if an error is encountered, log the error and send it back to the requestor + console.log(method+' business network connection failed'+error.message); + res.send(method+' business network connection failed'+error.message); + }); + } +}; diff --git a/Chapter08/Documentation/answers/js/z2b-provider_complete.js b/Chapter08/Documentation/answers/js/z2b-provider_complete.js index 99d667f..4a9e800 100644 --- a/Chapter08/Documentation/answers/js/z2b-provider_complete.js +++ b/Chapter08/Documentation/answers/js/z2b-provider_complete.js @@ -17,6 +17,10 @@ 'use strict'; let providerOrderDiv = 'providerOrderDiv'; +let p_alerts = []; +let p_notify = '#provider_notify'; +let p_count = '#provider_count'; +let p_id; /** * load the Provider User Experience @@ -24,30 +28,28 @@ let providerOrderDiv = 'providerOrderDiv'; function loadProviderUX () { let toLoad = 'provider.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupProvider(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupProvider(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupProvider(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupProvider(page);}); } } /** * load the Provider User Experience * @param {String} page - the name of the page to load - * @param {Integer} port - the port number to use */ -function setupProvider(page, port) +function setupProvider(page) { $('#body').empty(); $('#body').append(page); + if (p_alerts.length === 0) + {$(p_notify).removeClass('on'); $(p_notify).addClass('off'); } + else {$(p_notify).removeClass('off'); $(p_notify).addClass('on'); } updatePage('provider'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('provider_messages', msgPort); let _clear = $('#provider_clear'); let _list = $('#providerOrderStatus'); let _orderDiv = $('#'+providerOrderDiv); @@ -57,9 +59,15 @@ function setupProvider(page, port) $('#provider').append(p_string); $('#providerCompany').empty(); $('#providerCompany').append(providers[0].companyName); + p_id = providers[0].id; + z2bSubscribe('Provider', p_id); + // create a function to execute when the user selects a different provider $('#provider').on('change', function() { $('#providerCompany').empty(); _orderDiv.empty(); $('#provider_messages').empty(); $('#providerCompany').append(findMember($('#provider').find(':selected').val(),providers).companyName); + z2bUnSubscribe(p_id); + p_id = findMember($('#provider').find(':selected').text(),providers).id; + z2bSubscribe('Provider', p_id); }); } /** @@ -137,9 +145,6 @@ function formatProviderOrders(_target, _orders) _action += ''; b_string += '
    '+textPrompts.orderProcess.Refund.prompt+''; break; - case orderStatus.Cancelled.code: - _date = _arr[_idx].cancelled; - break; case orderStatus.Paid.code: _date = _arr[_idx].paid; break; @@ -150,7 +155,7 @@ function formatProviderOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    "+_curObj+""+_arr[_idx][_curObj]+"
    "+_curObj[0]+""+_curObj2+""+_arr2[_idx2][_curObj2[0]]+"
    '+_curObj+''+_arr[_idx][_curObj]+'
    '+_curObj[0]+''+_curObj2+''+_arr2[_idx2][_curObj2[0]]+'
    '; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+r_string+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.seller+findMember(_arr[_idx].seller.split('#')[1],sellers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+r_string+_button+''; _str+= '' for (let every in _arr[_idx].items) { @@ -286,18 +304,26 @@ function formatOrders(_target, _orders) // iterate through the page and make all of the different parts of the page active. // for (let each in _orders) - {(function(_idx, _arr) - { $('#b_btn_'+_idx).on('click', function () - { - let options = {}; - options.action = $('#b_action'+_idx).find(':selected').text(); - options.orderNo = $('#b_order'+_idx).text(); - options.participant = $('#buyer').val(); - if ((options.action === 'Dispute') || (options.action === 'Resolve')) {options.reason = $('#b_reason'+_idx).val();} - $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); - $.when($.post('/composer/client/orderAction', options)).done(function (_results) - { $('#buyer_messages').prepend(formatMessage(_results.result)); }); - }); - })(each, _orders) + {(function(_idx, _arr) + { $('#b_btn_'+_idx).on('click', function () + { + let options = {}; + options.action = $('#b_action'+_idx).find(':selected').text(); + options.orderNo = $('#b_order'+_idx).text(); + options.participant = $('#buyer').val(); + if ((options.action === 'Dispute') || (options.action === 'Resolve')) + {options.reason = $('#b_reason'+_idx).val();} + $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); + $.when($.post('/composer/client/orderAction', options)).done(function (_results) + { $('#buyer_messages').prepend(formatMessage(_results.result)); }); + }); + // use the notifyMe function to determine if this order is in the alert array. + // if it is, the highlight the $('#b_status'+_idx) html element by adding the 'highlight' class + if (notifyMe(b_alerts, _arr[_idx].id)) {$('#b_status'+_idx).addClass('highlight'); } + })(each, _orders); } + // reset the b_alerts array to a new array + b_alerts = new Array(); + // call the toggleAlerts function to reset the alert icon + toggleAlert($('#buyer_notify'), b_alerts, b_alerts.length); } \ No newline at end of file diff --git a/Chapter08/HTML/js/z2b-events.js b/Chapter08/HTML/js/z2b-events.js index f93de96..282f3ea 100644 --- a/Chapter08/HTML/js/z2b-events.js +++ b/Chapter08/HTML/js/z2b-events.js @@ -14,31 +14,79 @@ // z2c-events.js +'use strict'; + +let wsSocket; + +/** + * load the four initial user roles into a single page. + */ +function singleUX () +{ + let toLoad = 'singleUX.html'; + if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } + else{ + $.when($.get(toLoad)).done(function(_page) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } +} /** * load all of the members in the network for use in the different user experiences. This is a synchronous routine and is executed autormatically on web app start. * However, if this is a newly created network, then there are no members to retrieve and this will create four empty arrays */ function memberLoad () { - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - }); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + + }); +} +/** + * dropDummy() removes 'noop@dummy' from memberlist + * @param {String} _in - member id to ignore + */ +function dropDummy(_in) +{ + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} + return _a; } /** * load all of the members in the network for use in the different user experiences. This routine is designed for use if the network has been newly deployed and the web app was @@ -46,39 +94,190 @@ function memberLoad () */ function deferredMemberLoad() { - var d_prompts = $.Deferred(); - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - d_prompts.resolve(); - }).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + d_prompts.resolve(); + }).fail(d_prompts.reject); + return d_prompts.promise(); } /** * return an option list for use in an HTML '; - return _str; + return _str; +} +/** + * set up the server to listen for all events + */ +function goEventInitialize() +{ + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); +} + +/** + * @param {Event} _event - inbound Event + * @param {String} _id - subscriber target + * @param {String} _orderID - inbound order id + */ +function addNotification(_event, _id, _orderID) +{ + let method = 'addNotification'; + console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); + let type = getSubscriber(_id); + if (type === 'none') {return;} + switch(type) + { + case 'Buyer': + b_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(b_notify, b_alerts, b_count); + break; + case 'Seller': + s_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(s_notify, s_alerts, s_count); + break; + case 'Provider': + p_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(p_notify, p_alerts, p_count); + break; + case 'Shipper': + sh_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(sh_notify, sh_alerts, sh_count); + break; + case 'FinanceCo': + f_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(f_notify, f_alerts, f_count); + break; + default: + console.log(method+' default entered for: '+type); + break; + } +} +/** + * + * @param {jQuery} _target - jquery object to update + * @param {Array} _array - array of alerts for this member + * @param {jQuery} _count - jQuery object to hold alert count + */ +function toggleAlert(_target, _array, _count) +{ + if (_array.length < 1) + {$(_target).removeClass('on'); $(_target).addClass('off'); } + else {$(_count).empty(); $(_count).append(_array.length); + $(_target).removeClass('off'); $(_target).addClass('on'); } + +} +/** + * check to see if _id is subscribing + * @param {Integer} _id - member id to seek + * @returns {String} - type of member + */ +function getSubscriber(_id) +{ + let type = 'none'; + for (let each in subscribers){(function(_idx, _arr){if (_arr[_idx].id === _id){type=_arr[_idx].type;}})(each, subscribers);} + return(type); +} +/** + * subscribe to events + * @param {String} _type - member type + * @param {String} _id - member id + */ +function z2bSubscribe(_type, _id) +{ + subscribers.push({'type': _type, 'id': _id}); +} +/** + * Unsubscribe to events + * @param {String} _id - member id to remove + */ +function z2bUnSubscribe(_id) +{ + let _s1 = subscribers; + let _s2 = []; + for (let each in _s1) {(function(_idx, _arr){if (_arr[_idx] != _id){_s2.push(_arr[_idx]);}})(each, _s1);} + subscribers = _s2; +} +/** + * notifyMe + * @param {Array} _alerts - array of alerts + * @param {String} _id - orderID + * @returns {Boolean} - true if found, false if not found + */ +function notifyMe (_alerts, _id) +{ + let b_h = false; + for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} + return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter08/HTML/js/z2b-initiate.js b/Chapter08/HTML/js/z2b-initiate.js index 290ef03..7ba4493 100644 --- a/Chapter08/HTML/js/z2b-initiate.js +++ b/Chapter08/HTML/js/z2b-initiate.js @@ -13,41 +13,52 @@ */ // z2c-initiate.js -var connectionProfileName = "z2b-test-profile"; -var networkFile = "zerotoblockchain-network.bna" -var businessNetwork = "zerotoblockchain-network"; - -var buyers, sellers, providers, shippers; -var s_string, p_string, sh_string; - -var orderStatus = { - Created: {code: 1, text: 'Order Created'}, - Bought: {code: 2, text: 'Order Purchased'}, - Cancelled: {code: 3, text: 'Order Cancelled'}, - Ordered: {code: 4, text: 'Order Submitted to Provider'}, - ShipRequest: {code: 5, text: 'Shipping Requested'}, - Delivered: {code: 6, text: 'Order Delivered'}, - Delivering: {code: 15, text: 'Order being Delivered'}, - Backordered: {code: 7, text: 'Order Backordered'}, - Dispute: {code: 8, text: 'Order Disputed'}, - Resolve: {code: 9, text: 'Order Dispute Resolved'}, - PayRequest: {code: 10, text: 'Payment Requested'}, - Authorize: {code: 11, text: 'Payment Approved'}, - Paid: {code: 14, text: 'Payment Processed'}, - Refund: {code: 12, text: 'Order Refund Requested'}, - Refunded: {code: 13, text: 'Order Refunded'} + +'use strict'; + +let connectionProfileName = 'z2b-test-profile'; +let networkFile = 'zerotoblockchain-network.bna'; +let businessNetwork = 'zerotoblockchain-network'; + +let host_address = window.location.host; + +let buyers = new Array(); +let sellers= new Array(); +let providers= new Array(); +let shippers= new Array(); + +let s_string, p_string, sh_string; + +let orderStatus = { + Created: {code: 1, text: 'Order Created'}, + Bought: {code: 2, text: 'Order Purchased'}, + Cancelled: {code: 3, text: 'Order Cancelled'}, + Ordered: {code: 4, text: 'Order Submitted to Provider'}, + ShipRequest: {code: 5, text: 'Shipping Requested'}, + Delivered: {code: 6, text: 'Order Delivered'}, + Delivering: {code: 15, text: 'Order being Delivered'}, + Backordered: {code: 7, text: 'Order Backordered'}, + Dispute: {code: 8, text: 'Order Disputed'}, + Resolve: {code: 9, text: 'Order Dispute Resolved'}, + PayRequest: {code: 10, text: 'Payment Requested'}, + Authorize: {code: 11, text: 'Payment Approved'}, + Paid: {code: 14, text: 'Payment Processed'}, + Refund: {code: 12, text: 'Order Refund Requested'}, + Refunded: {code: 13, text: 'Order Refunded'} }; /** * standard home page initialization routine * Refer to this by {@link initPage()}. */ - function initPage () +function initPage () { - // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English - goMultiLingual("US_English", "index"); - // singleUX loads the members already present in the network - memberLoad(); - // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring - getChainEvents(); + // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English + goMultiLingual('US_English', 'index'); + // singleUX loads the members already present in the network + memberLoad(); + // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring + getChainEvents(); + // get the asynch port + wsConnect(); } diff --git a/Chapter08/HTML/js/z2b-seller.js b/Chapter08/HTML/js/z2b-seller.js index ecc7209..19072a8 100644 --- a/Chapter08/HTML/js/z2b-seller.js +++ b/Chapter08/HTML/js/z2b-seller.js @@ -16,36 +16,38 @@ 'use strict'; let sellerOrderDiv = 'sellerOrderDiv'; - +let s_alerts = []; +let s_notify = '#seller_notify'; +let s_count = '#seller_count'; +let s_id; /** * load the administration Seller Experience */ function loadSellerUX () { let toLoad = 'seller.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupSeller(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupSeller(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupSeller(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupSeller(page);}); } } /** * load the administration User Experience * @param {String} page - page to load - * @param {Integer} port - web socket port to use */ -function setupSeller(page, port) +function setupSeller(page) { $('#body').empty(); $('#body').append(page); + if (s_alerts.length == 0) + {$(s_notify).removeClass('on'); $(s_notify).addClass('off'); } + else {$(s_notify).removeClass('off'); $(s_notify).addClass('on'); } updatePage('seller'); - msgPort = port.port; - wsDisplay('seller_messages', msgPort); let _clear = $('#seller_clear'); let _list = $('#sellerOrderStatus'); let _orderDiv = $('#'+sellerOrderDiv); @@ -58,9 +60,15 @@ function setupSeller(page, port) $('#seller').append(s_string); $('#sellerCompany').empty(); $('#sellerCompany').append(sellers[0].companyName); - $('#seller').on('change', function() { + s_id = sellers[0].id; + z2bSubscribe('Seller', s_id); + // create a function to execute when the user selects a different provider + $('#seller').on('change', function() { $('#sellerCompany').empty(); _orderDiv.empty(); $('#seller_messages').empty(); $('#sellerCompany').append(findMember($('#seller').find(':selected').val(),sellers).companyName); + z2bUnSubscribe(s_id); + s_id = findMember($('#seller').find(':selected').text(),sellers).id; + z2bSubscribe('Seller', s_id); }); } /** @@ -151,7 +159,7 @@ function formatSellerOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    '; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; @@ -143,7 +151,7 @@ function formatShipperOrders(_target, _orders) console.log('shipper _action: '+_action); if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+_statusText+''+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+'Buyer: '+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+_statusText+''+_button+''; _str+= '' for (let every in _arr[_idx].items) {(function(_idx2, _arr2) @@ -173,6 +181,9 @@ function formatShipperOrders(_target, _orders) $('#shipper_messages').prepend(formatMessage(_results.result)); }); }); + if (notifyMe(sh_alerts, _arr[_idx].id)) {$("#sh_status"+_idx).addClass('highlight'); } })(each, _orders); } -} \ No newline at end of file + sh_alerts = new Array(); + toggleAlert($('#shipper_notify'), sh_alerts, sh_alerts.length); + } \ No newline at end of file diff --git a/Chapter09/HTML/favicon.ico b/Chapter09/HTML/favicon.ico old mode 100755 new mode 100644 index fc9e25d..3dbe425 Binary files a/Chapter09/HTML/favicon.ico and b/Chapter09/HTML/favicon.ico differ diff --git a/Chapter09/HTML/js/z2b-admin.js b/Chapter09/HTML/js/z2b-admin.js index 67f421a..f3c3ffc 100644 --- a/Chapter09/HTML/js/z2b-admin.js +++ b/Chapter09/HTML/js/z2b-admin.js @@ -18,7 +18,6 @@ let creds; let connection; -let msgPort = null; let _blctr = 0; /** @@ -34,19 +33,6 @@ function loadAdminUX () listMemRegistries(); }); } -/** - * connect to the provided web socket - * @param {String} _target - location to post messages - * @param {Integer} _port - web socket port # - */ -function wsDisplay(_target, _port) -{ - let content = $('#'+_target); - let wsSocket = new WebSocket('ws://localhost:'+_port); - wsSocket.onopen = function () {wsSocket.send('connected to client');}; - wsSocket.onmessage = function (message) {content.append(formatMessage(message.data));}; - wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ' + error);}; -} /** * list the available business networks */ @@ -361,7 +347,7 @@ function preLoad() $('#body').empty(); let options = {}; $.when($.post('/setup/autoLoad', options)).done(function (_results) - { msgPort = _results.port; wsDisplay('body', msgPort); }); + { console.log('Autoload Initiated'); $('#body').append('

    Autoload Initiated

    '); }); } /** @@ -754,28 +740,9 @@ function getHistorian() */ function getChainEvents() { - $.when($.get('fabric/getChainEvents')).done(function(_res) - { let _str = '

    Get Chain events requested. Sending to port: '+_res.port+'

    '; - let content = $('#blockchain'); - let csSocket = new WebSocket('ws://localhost:'+_res.port); - csSocket.onopen = function () {csSocket.send('connected to client');}; - csSocket.onmessage = function (message) { - _blctr ++; - if (message.data !== 'connected') - {$(content).append('block '+JSON.parse(message.data).header.number+'
    Hash: '+JSON.parse(message.data).header.data_hash+'
    '); - if (_blctr > 4) {let leftPos = $(content).scrollLeft(); $(content).animate({scrollLeft: leftPos + 300}, 250);} - } - }; - csSocket.onerror = function (error) {console.log('WebSocket error: ' + error);}; - $('#admin-forms').empty(); - $('#admin-forms').append(_str); + $.when($.get('/fabric/getChainEvents')).done(function(_res) + { $('#body').append('

    Get Chain events requested.

    '); + let _host = (host_address.slice(0,9) === 'localhost') ? 'localhost' : host_address; + console.log('getChainEvents host_address: '+_host); }); -} -/** - * display blockchain updates - */ -function displayAdminUpdate() -{ - let toLoad = 'adminHelp.html'; - $.when($.get(toLoad)).done(function(_page){$('#admin-forms').empty(); $('#admin-forms').append(_page);}); } \ No newline at end of file diff --git a/Chapter09/HTML/js/z2b-buyer.js b/Chapter09/HTML/js/z2b-buyer.js index 535f938..2a4cffc 100644 --- a/Chapter09/HTML/js/z2b-buyer.js +++ b/Chapter09/HTML/js/z2b-buyer.js @@ -15,6 +15,10 @@ // z2c-buyer.js 'use strict'; +let b_notify = '#buyer_notify'; +let b_count = '#buyer_count'; +let b_id = ''; +let b_alerts; let orderDiv = 'orderDiv'; let itemTable = {}; @@ -28,31 +32,32 @@ function loadBuyerUX () { // get the html page to load let toLoad = 'buyer.html'; - // get the port to use for web socket communications with the server - getPort(); // if (buyers.length === 0) then autoLoad() was not successfully run before this web app starts, so the sie of the buyer list is zero // assume user has run autoLoad and rebuild member list // if autoLoad not yet run, then member list length will still be zero if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupBuyer(page[0], port[0]);}); - } - else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupBuyer(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupBuyer(page);}); + } + else{ + $.when($.get(toLoad)).done(function (page) + {setupBuyer(page);}); + } } -} - -function setupBuyer(page, port) -{ + + function setupBuyer(page) + { // empty the hetml element that will hold this page $('#body').empty(); $('#body').append(page); - // update the text on the page using the prompt data for the selected language + // empty the buyer alerts array + b_alerts = []; + // if there are no alerts, then remove the 'on' class and add the 'off' class + if (b_alerts.length === 0) + {$(b_notify).removeClass('on'); $(b_notify).addClass('off'); } + else {$(b_notify).removeClass('off'); $(b_notify).addClass('on'); } + // update the text on the page using the prompt data for the selected language updatePage('buyer'); - msgPort = port.port; - // connect to the web socket and tell the web socket where to display messages - wsDisplay('buyer_messages', msgPort); // enable the buttons to process an onClick event let _create = $('#newOrder'); let _list = $('#orderStatus'); @@ -67,8 +72,21 @@ function setupBuyer(page, port) } // display the name of the current buyer $('#company')[0].innerText = buyers[0].companyName; - // create a function to execute when the user selects a different buyer - $('#buyer').on('change', function() { _orderDiv.empty(); $('#buyer_messages').empty(); $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; }); + // save the current buyer id as b_id + b_id = buyers[0].id; + // subscribe to events + z2bSubscribe('Buyer', b_id); + // create a function to execute when the user selects a different buyer + $('#buyer').on('change', function() + { _orderDiv.empty(); $('#buyer_messages').empty(); + $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; + // unsubscribe the current buyer + z2bUnSubscribe(b_id); + // get the new buyer id + b_id = findMember($('#buyer').find(':selected').text(),buyers).id; + // subscribe the new buyer + z2bSubscribe('Buyer', b_id); + }); } /** @@ -97,7 +115,7 @@ function displayOrderForm() $('#amount').append('$'+totalAmount+'.00'); // build a select list for the items let _str = ''; - for (let each in itemTable){(function(_idx, _arr){_str+=''})(each, itemTable)} + for (let each in itemTable){(function(_idx, _arr){_str+='';})(each, itemTable);} $('#items').empty(); $('#items').append(_str); $('#cancelNewOrder').on('click', function (){_orderDiv.empty();}); @@ -185,8 +203,8 @@ function listOrders() * used by the listOrders() function * formats the orders for a buyer. Orders to be formatted are provided in the _orders array * output replaces the current contents of the html element identified by _target - * @param _target - string with div id prefaced by # - * @param _orders - array with order objects + * @param {String} _target - string with div id prefaced by # + * @param {Array} _orders - array with order objects */ function formatOrders(_target, _orders) { @@ -267,7 +285,7 @@ function formatOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    '; - _str += ''+_action+r_string+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.seller+findMember(_arr[_idx].seller.split('#')[1],sellers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+r_string+_button+''; _str+= '' for (let every in _arr[_idx].items) { @@ -286,18 +304,26 @@ function formatOrders(_target, _orders) // iterate through the page and make all of the different parts of the page active. // for (let each in _orders) - {(function(_idx, _arr) - { $('#b_btn_'+_idx).on('click', function () - { - let options = {}; - options.action = $('#b_action'+_idx).find(':selected').text(); - options.orderNo = $('#b_order'+_idx).text(); - options.participant = $('#buyer').val(); - if ((options.action === 'Dispute') || (options.action === 'Resolve')) {options.reason = $('#b_reason'+_idx).val();} - $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); - $.when($.post('/composer/client/orderAction', options)).done(function (_results) - { $('#buyer_messages').prepend(formatMessage(_results.result)); }); - }); - })(each, _orders) + {(function(_idx, _arr) + { $('#b_btn_'+_idx).on('click', function () + { + let options = {}; + options.action = $('#b_action'+_idx).find(':selected').text(); + options.orderNo = $('#b_order'+_idx).text(); + options.participant = $('#buyer').val(); + if ((options.action === 'Dispute') || (options.action === 'Resolve')) + {options.reason = $('#b_reason'+_idx).val();} + $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); + $.when($.post('/composer/client/orderAction', options)).done(function (_results) + { $('#buyer_messages').prepend(formatMessage(_results.result)); }); + }); + // use the notifyMe function to determine if this order is in the alert array. + // if it is, the highlight the $('#b_status'+_idx) html element by adding the 'highlight' class + if (notifyMe(b_alerts, _arr[_idx].id)) {$('#b_status'+_idx).addClass('highlight'); } + })(each, _orders); } + // reset the b_alerts array to a new array + b_alerts = new Array(); + // call the toggleAlerts function to reset the alert icon + toggleAlert($('#buyer_notify'), b_alerts, b_alerts.length); } \ No newline at end of file diff --git a/Chapter09/HTML/js/z2b-events.js b/Chapter09/HTML/js/z2b-events.js index f93de96..282f3ea 100644 --- a/Chapter09/HTML/js/z2b-events.js +++ b/Chapter09/HTML/js/z2b-events.js @@ -14,31 +14,79 @@ // z2c-events.js +'use strict'; + +let wsSocket; + +/** + * load the four initial user roles into a single page. + */ +function singleUX () +{ + let toLoad = 'singleUX.html'; + if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } + else{ + $.when($.get(toLoad)).done(function(_page) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } +} /** * load all of the members in the network for use in the different user experiences. This is a synchronous routine and is executed autormatically on web app start. * However, if this is a newly created network, then there are no members to retrieve and this will create four empty arrays */ function memberLoad () { - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - }); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + + }); +} +/** + * dropDummy() removes 'noop@dummy' from memberlist + * @param {String} _in - member id to ignore + */ +function dropDummy(_in) +{ + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} + return _a; } /** * load all of the members in the network for use in the different user experiences. This routine is designed for use if the network has been newly deployed and the web app was @@ -46,39 +94,190 @@ function memberLoad () */ function deferredMemberLoad() { - var d_prompts = $.Deferred(); - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - d_prompts.resolve(); - }).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + d_prompts.resolve(); + }).fail(d_prompts.reject); + return d_prompts.promise(); } /** * return an option list for use in an HTML '; - return _str; + return _str; +} +/** + * set up the server to listen for all events + */ +function goEventInitialize() +{ + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); +} + +/** + * @param {Event} _event - inbound Event + * @param {String} _id - subscriber target + * @param {String} _orderID - inbound order id + */ +function addNotification(_event, _id, _orderID) +{ + let method = 'addNotification'; + console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); + let type = getSubscriber(_id); + if (type === 'none') {return;} + switch(type) + { + case 'Buyer': + b_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(b_notify, b_alerts, b_count); + break; + case 'Seller': + s_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(s_notify, s_alerts, s_count); + break; + case 'Provider': + p_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(p_notify, p_alerts, p_count); + break; + case 'Shipper': + sh_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(sh_notify, sh_alerts, sh_count); + break; + case 'FinanceCo': + f_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(f_notify, f_alerts, f_count); + break; + default: + console.log(method+' default entered for: '+type); + break; + } +} +/** + * + * @param {jQuery} _target - jquery object to update + * @param {Array} _array - array of alerts for this member + * @param {jQuery} _count - jQuery object to hold alert count + */ +function toggleAlert(_target, _array, _count) +{ + if (_array.length < 1) + {$(_target).removeClass('on'); $(_target).addClass('off'); } + else {$(_count).empty(); $(_count).append(_array.length); + $(_target).removeClass('off'); $(_target).addClass('on'); } + +} +/** + * check to see if _id is subscribing + * @param {Integer} _id - member id to seek + * @returns {String} - type of member + */ +function getSubscriber(_id) +{ + let type = 'none'; + for (let each in subscribers){(function(_idx, _arr){if (_arr[_idx].id === _id){type=_arr[_idx].type;}})(each, subscribers);} + return(type); +} +/** + * subscribe to events + * @param {String} _type - member type + * @param {String} _id - member id + */ +function z2bSubscribe(_type, _id) +{ + subscribers.push({'type': _type, 'id': _id}); +} +/** + * Unsubscribe to events + * @param {String} _id - member id to remove + */ +function z2bUnSubscribe(_id) +{ + let _s1 = subscribers; + let _s2 = []; + for (let each in _s1) {(function(_idx, _arr){if (_arr[_idx] != _id){_s2.push(_arr[_idx]);}})(each, _s1);} + subscribers = _s2; +} +/** + * notifyMe + * @param {Array} _alerts - array of alerts + * @param {String} _id - orderID + * @returns {Boolean} - true if found, false if not found + */ +function notifyMe (_alerts, _id) +{ + let b_h = false; + for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} + return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter09/HTML/js/z2b-initiate.js b/Chapter09/HTML/js/z2b-initiate.js index 290ef03..7ba4493 100644 --- a/Chapter09/HTML/js/z2b-initiate.js +++ b/Chapter09/HTML/js/z2b-initiate.js @@ -13,41 +13,52 @@ */ // z2c-initiate.js -var connectionProfileName = "z2b-test-profile"; -var networkFile = "zerotoblockchain-network.bna" -var businessNetwork = "zerotoblockchain-network"; - -var buyers, sellers, providers, shippers; -var s_string, p_string, sh_string; - -var orderStatus = { - Created: {code: 1, text: 'Order Created'}, - Bought: {code: 2, text: 'Order Purchased'}, - Cancelled: {code: 3, text: 'Order Cancelled'}, - Ordered: {code: 4, text: 'Order Submitted to Provider'}, - ShipRequest: {code: 5, text: 'Shipping Requested'}, - Delivered: {code: 6, text: 'Order Delivered'}, - Delivering: {code: 15, text: 'Order being Delivered'}, - Backordered: {code: 7, text: 'Order Backordered'}, - Dispute: {code: 8, text: 'Order Disputed'}, - Resolve: {code: 9, text: 'Order Dispute Resolved'}, - PayRequest: {code: 10, text: 'Payment Requested'}, - Authorize: {code: 11, text: 'Payment Approved'}, - Paid: {code: 14, text: 'Payment Processed'}, - Refund: {code: 12, text: 'Order Refund Requested'}, - Refunded: {code: 13, text: 'Order Refunded'} + +'use strict'; + +let connectionProfileName = 'z2b-test-profile'; +let networkFile = 'zerotoblockchain-network.bna'; +let businessNetwork = 'zerotoblockchain-network'; + +let host_address = window.location.host; + +let buyers = new Array(); +let sellers= new Array(); +let providers= new Array(); +let shippers= new Array(); + +let s_string, p_string, sh_string; + +let orderStatus = { + Created: {code: 1, text: 'Order Created'}, + Bought: {code: 2, text: 'Order Purchased'}, + Cancelled: {code: 3, text: 'Order Cancelled'}, + Ordered: {code: 4, text: 'Order Submitted to Provider'}, + ShipRequest: {code: 5, text: 'Shipping Requested'}, + Delivered: {code: 6, text: 'Order Delivered'}, + Delivering: {code: 15, text: 'Order being Delivered'}, + Backordered: {code: 7, text: 'Order Backordered'}, + Dispute: {code: 8, text: 'Order Disputed'}, + Resolve: {code: 9, text: 'Order Dispute Resolved'}, + PayRequest: {code: 10, text: 'Payment Requested'}, + Authorize: {code: 11, text: 'Payment Approved'}, + Paid: {code: 14, text: 'Payment Processed'}, + Refund: {code: 12, text: 'Order Refund Requested'}, + Refunded: {code: 13, text: 'Order Refunded'} }; /** * standard home page initialization routine * Refer to this by {@link initPage()}. */ - function initPage () +function initPage () { - // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English - goMultiLingual("US_English", "index"); - // singleUX loads the members already present in the network - memberLoad(); - // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring - getChainEvents(); + // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English + goMultiLingual('US_English', 'index'); + // singleUX loads the members already present in the network + memberLoad(); + // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring + getChainEvents(); + // get the asynch port + wsConnect(); } diff --git a/Chapter09/HTML/js/z2b-provider.js b/Chapter09/HTML/js/z2b-provider.js index 99d667f..4a9e800 100644 --- a/Chapter09/HTML/js/z2b-provider.js +++ b/Chapter09/HTML/js/z2b-provider.js @@ -17,6 +17,10 @@ 'use strict'; let providerOrderDiv = 'providerOrderDiv'; +let p_alerts = []; +let p_notify = '#provider_notify'; +let p_count = '#provider_count'; +let p_id; /** * load the Provider User Experience @@ -24,30 +28,28 @@ let providerOrderDiv = 'providerOrderDiv'; function loadProviderUX () { let toLoad = 'provider.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupProvider(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupProvider(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupProvider(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupProvider(page);}); } } /** * load the Provider User Experience * @param {String} page - the name of the page to load - * @param {Integer} port - the port number to use */ -function setupProvider(page, port) +function setupProvider(page) { $('#body').empty(); $('#body').append(page); + if (p_alerts.length === 0) + {$(p_notify).removeClass('on'); $(p_notify).addClass('off'); } + else {$(p_notify).removeClass('off'); $(p_notify).addClass('on'); } updatePage('provider'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('provider_messages', msgPort); let _clear = $('#provider_clear'); let _list = $('#providerOrderStatus'); let _orderDiv = $('#'+providerOrderDiv); @@ -57,9 +59,15 @@ function setupProvider(page, port) $('#provider').append(p_string); $('#providerCompany').empty(); $('#providerCompany').append(providers[0].companyName); + p_id = providers[0].id; + z2bSubscribe('Provider', p_id); + // create a function to execute when the user selects a different provider $('#provider').on('change', function() { $('#providerCompany').empty(); _orderDiv.empty(); $('#provider_messages').empty(); $('#providerCompany').append(findMember($('#provider').find(':selected').val(),providers).companyName); + z2bUnSubscribe(p_id); + p_id = findMember($('#provider').find(':selected').text(),providers).id; + z2bSubscribe('Provider', p_id); }); } /** @@ -137,9 +145,6 @@ function formatProviderOrders(_target, _orders) _action += ''; b_string += '
    '+textPrompts.orderProcess.Refund.prompt+''; break; - case orderStatus.Cancelled.code: - _date = _arr[_idx].cancelled; - break; case orderStatus.Paid.code: _date = _arr[_idx].paid; break; @@ -150,7 +155,7 @@ function formatProviderOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    '; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; @@ -148,7 +154,7 @@ function formatFinanceOrders(_target, _orders) let _len = 'resource:org.acme.Z2BTestNetwork.Buyer#'.length; let _buyer = _arr[_idx].buyer.substring(_len, _arr[_idx].buyer.length); _str += '
    '; - _str += ''+_action+''+_button+'
    Order #StatusTotalBuyer: '+findMember(_buyer,buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+''+_button+''; _str+= formatDetail(_idx, _arr[_idx]); })(each, _orders); } @@ -171,11 +177,17 @@ function formatFinanceOrders(_target, _orders) $('#finance_messages').prepend(formatMessage(_results.result)); }); }); + if (notifyMe(f_alerts, _arr[_idx].id)) {$("#f_status"+_idx).addClass('highlight'); } })(each, _orders); } + f_alerts = new Array(); + toggleAlert($('#financeCo_notify'), f_alerts, f_alerts.length); } /** * format the accordian with the details for this order + * @param {Integer} _cur - offset into order array + * @param {JSON} _order - JSON object with current order data + * @returns {String} - html string to append to browser page */ function formatDetail(_cur, _order) { diff --git a/Chapter10/HTML/favicon.ico b/Chapter10/HTML/favicon.ico old mode 100755 new mode 100644 index fc9e25d..3dbe425 Binary files a/Chapter10/HTML/favicon.ico and b/Chapter10/HTML/favicon.ico differ diff --git a/Chapter10/HTML/js/z2b-admin.js b/Chapter10/HTML/js/z2b-admin.js index 67f421a..f3c3ffc 100644 --- a/Chapter10/HTML/js/z2b-admin.js +++ b/Chapter10/HTML/js/z2b-admin.js @@ -18,7 +18,6 @@ let creds; let connection; -let msgPort = null; let _blctr = 0; /** @@ -34,19 +33,6 @@ function loadAdminUX () listMemRegistries(); }); } -/** - * connect to the provided web socket - * @param {String} _target - location to post messages - * @param {Integer} _port - web socket port # - */ -function wsDisplay(_target, _port) -{ - let content = $('#'+_target); - let wsSocket = new WebSocket('ws://localhost:'+_port); - wsSocket.onopen = function () {wsSocket.send('connected to client');}; - wsSocket.onmessage = function (message) {content.append(formatMessage(message.data));}; - wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ' + error);}; -} /** * list the available business networks */ @@ -361,7 +347,7 @@ function preLoad() $('#body').empty(); let options = {}; $.when($.post('/setup/autoLoad', options)).done(function (_results) - { msgPort = _results.port; wsDisplay('body', msgPort); }); + { console.log('Autoload Initiated'); $('#body').append('

    Autoload Initiated

    '); }); } /** @@ -754,28 +740,9 @@ function getHistorian() */ function getChainEvents() { - $.when($.get('fabric/getChainEvents')).done(function(_res) - { let _str = '

    Get Chain events requested. Sending to port: '+_res.port+'

    '; - let content = $('#blockchain'); - let csSocket = new WebSocket('ws://localhost:'+_res.port); - csSocket.onopen = function () {csSocket.send('connected to client');}; - csSocket.onmessage = function (message) { - _blctr ++; - if (message.data !== 'connected') - {$(content).append('block '+JSON.parse(message.data).header.number+'
    Hash: '+JSON.parse(message.data).header.data_hash+'
    '); - if (_blctr > 4) {let leftPos = $(content).scrollLeft(); $(content).animate({scrollLeft: leftPos + 300}, 250);} - } - }; - csSocket.onerror = function (error) {console.log('WebSocket error: ' + error);}; - $('#admin-forms').empty(); - $('#admin-forms').append(_str); + $.when($.get('/fabric/getChainEvents')).done(function(_res) + { $('#body').append('

    Get Chain events requested.

    '); + let _host = (host_address.slice(0,9) === 'localhost') ? 'localhost' : host_address; + console.log('getChainEvents host_address: '+_host); }); -} -/** - * display blockchain updates - */ -function displayAdminUpdate() -{ - let toLoad = 'adminHelp.html'; - $.when($.get(toLoad)).done(function(_page){$('#admin-forms').empty(); $('#admin-forms').append(_page);}); } \ No newline at end of file diff --git a/Chapter10/HTML/js/z2b-buyer.js b/Chapter10/HTML/js/z2b-buyer.js index 535f938..2a4cffc 100644 --- a/Chapter10/HTML/js/z2b-buyer.js +++ b/Chapter10/HTML/js/z2b-buyer.js @@ -15,6 +15,10 @@ // z2c-buyer.js 'use strict'; +let b_notify = '#buyer_notify'; +let b_count = '#buyer_count'; +let b_id = ''; +let b_alerts; let orderDiv = 'orderDiv'; let itemTable = {}; @@ -28,31 +32,32 @@ function loadBuyerUX () { // get the html page to load let toLoad = 'buyer.html'; - // get the port to use for web socket communications with the server - getPort(); // if (buyers.length === 0) then autoLoad() was not successfully run before this web app starts, so the sie of the buyer list is zero // assume user has run autoLoad and rebuild member list // if autoLoad not yet run, then member list length will still be zero if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupBuyer(page[0], port[0]);}); - } - else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupBuyer(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupBuyer(page);}); + } + else{ + $.when($.get(toLoad)).done(function (page) + {setupBuyer(page);}); + } } -} - -function setupBuyer(page, port) -{ + + function setupBuyer(page) + { // empty the hetml element that will hold this page $('#body').empty(); $('#body').append(page); - // update the text on the page using the prompt data for the selected language + // empty the buyer alerts array + b_alerts = []; + // if there are no alerts, then remove the 'on' class and add the 'off' class + if (b_alerts.length === 0) + {$(b_notify).removeClass('on'); $(b_notify).addClass('off'); } + else {$(b_notify).removeClass('off'); $(b_notify).addClass('on'); } + // update the text on the page using the prompt data for the selected language updatePage('buyer'); - msgPort = port.port; - // connect to the web socket and tell the web socket where to display messages - wsDisplay('buyer_messages', msgPort); // enable the buttons to process an onClick event let _create = $('#newOrder'); let _list = $('#orderStatus'); @@ -67,8 +72,21 @@ function setupBuyer(page, port) } // display the name of the current buyer $('#company')[0].innerText = buyers[0].companyName; - // create a function to execute when the user selects a different buyer - $('#buyer').on('change', function() { _orderDiv.empty(); $('#buyer_messages').empty(); $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; }); + // save the current buyer id as b_id + b_id = buyers[0].id; + // subscribe to events + z2bSubscribe('Buyer', b_id); + // create a function to execute when the user selects a different buyer + $('#buyer').on('change', function() + { _orderDiv.empty(); $('#buyer_messages').empty(); + $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; + // unsubscribe the current buyer + z2bUnSubscribe(b_id); + // get the new buyer id + b_id = findMember($('#buyer').find(':selected').text(),buyers).id; + // subscribe the new buyer + z2bSubscribe('Buyer', b_id); + }); } /** @@ -97,7 +115,7 @@ function displayOrderForm() $('#amount').append('$'+totalAmount+'.00'); // build a select list for the items let _str = ''; - for (let each in itemTable){(function(_idx, _arr){_str+=''})(each, itemTable)} + for (let each in itemTable){(function(_idx, _arr){_str+='';})(each, itemTable);} $('#items').empty(); $('#items').append(_str); $('#cancelNewOrder').on('click', function (){_orderDiv.empty();}); @@ -185,8 +203,8 @@ function listOrders() * used by the listOrders() function * formats the orders for a buyer. Orders to be formatted are provided in the _orders array * output replaces the current contents of the html element identified by _target - * @param _target - string with div id prefaced by # - * @param _orders - array with order objects + * @param {String} _target - string with div id prefaced by # + * @param {Array} _orders - array with order objects */ function formatOrders(_target, _orders) { @@ -267,7 +285,7 @@ function formatOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+r_string+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.seller+findMember(_arr[_idx].seller.split('#')[1],sellers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+r_string+_button+''; _str+= '' for (let every in _arr[_idx].items) { @@ -286,18 +304,26 @@ function formatOrders(_target, _orders) // iterate through the page and make all of the different parts of the page active. // for (let each in _orders) - {(function(_idx, _arr) - { $('#b_btn_'+_idx).on('click', function () - { - let options = {}; - options.action = $('#b_action'+_idx).find(':selected').text(); - options.orderNo = $('#b_order'+_idx).text(); - options.participant = $('#buyer').val(); - if ((options.action === 'Dispute') || (options.action === 'Resolve')) {options.reason = $('#b_reason'+_idx).val();} - $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); - $.when($.post('/composer/client/orderAction', options)).done(function (_results) - { $('#buyer_messages').prepend(formatMessage(_results.result)); }); - }); - })(each, _orders) + {(function(_idx, _arr) + { $('#b_btn_'+_idx).on('click', function () + { + let options = {}; + options.action = $('#b_action'+_idx).find(':selected').text(); + options.orderNo = $('#b_order'+_idx).text(); + options.participant = $('#buyer').val(); + if ((options.action === 'Dispute') || (options.action === 'Resolve')) + {options.reason = $('#b_reason'+_idx).val();} + $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); + $.when($.post('/composer/client/orderAction', options)).done(function (_results) + { $('#buyer_messages').prepend(formatMessage(_results.result)); }); + }); + // use the notifyMe function to determine if this order is in the alert array. + // if it is, the highlight the $('#b_status'+_idx) html element by adding the 'highlight' class + if (notifyMe(b_alerts, _arr[_idx].id)) {$('#b_status'+_idx).addClass('highlight'); } + })(each, _orders); } + // reset the b_alerts array to a new array + b_alerts = new Array(); + // call the toggleAlerts function to reset the alert icon + toggleAlert($('#buyer_notify'), b_alerts, b_alerts.length); } \ No newline at end of file diff --git a/Chapter10/HTML/js/z2b-events.js b/Chapter10/HTML/js/z2b-events.js index f93de96..282f3ea 100644 --- a/Chapter10/HTML/js/z2b-events.js +++ b/Chapter10/HTML/js/z2b-events.js @@ -14,31 +14,79 @@ // z2c-events.js +'use strict'; + +let wsSocket; + +/** + * load the four initial user roles into a single page. + */ +function singleUX () +{ + let toLoad = 'singleUX.html'; + if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } + else{ + $.when($.get(toLoad)).done(function(_page) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); + } +} /** * load all of the members in the network for use in the different user experiences. This is a synchronous routine and is executed autormatically on web app start. * However, if this is a newly created network, then there are no members to retrieve and this will create four empty arrays */ function memberLoad () { - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - }); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + + }); +} +/** + * dropDummy() removes 'noop@dummy' from memberlist + * @param {String} _in - member id to ignore + */ +function dropDummy(_in) +{ + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} + return _a; } /** * load all of the members in the network for use in the different user experiences. This routine is designed for use if the network has been newly deployed and the web app was @@ -46,39 +94,190 @@ function memberLoad () */ function deferredMemberLoad() { - var d_prompts = $.Deferred(); - var options = {}; - options.registry = 'Seller'; - var options2 = {}; - options2.registry = 'Buyer'; - var options3 = {}; - options3.registry = 'Provider'; - var options4 = {}; - options4.registry = 'Shipper'; - $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), - $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) - { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members - p_string = _getMembers(providers); - shippers = _shippers[0].members - sh_string = _getMembers(shippers); - d_prompts.resolve(); - }).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; + options.registry = 'Seller'; + let options2 = {}; + options2.registry = 'Buyer'; + let options3 = {}; + options3.registry = 'Provider'; + let options4 = {}; + options4.registry = 'Shipper'; + $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), + $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) + { + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + d_prompts.resolve(); + }).fail(d_prompts.reject); + return d_prompts.promise(); } /** * return an option list for use in an HTML '; - return _str; + return _str; +} +/** + * set up the server to listen for all events + */ +function goEventInitialize() +{ + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); +} + +/** + * @param {Event} _event - inbound Event + * @param {String} _id - subscriber target + * @param {String} _orderID - inbound order id + */ +function addNotification(_event, _id, _orderID) +{ + let method = 'addNotification'; + console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); + let type = getSubscriber(_id); + if (type === 'none') {return;} + switch(type) + { + case 'Buyer': + b_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(b_notify, b_alerts, b_count); + break; + case 'Seller': + s_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(s_notify, s_alerts, s_count); + break; + case 'Provider': + p_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(p_notify, p_alerts, p_count); + break; + case 'Shipper': + sh_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(sh_notify, sh_alerts, sh_count); + break; + case 'FinanceCo': + f_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(f_notify, f_alerts, f_count); + break; + default: + console.log(method+' default entered for: '+type); + break; + } +} +/** + * + * @param {jQuery} _target - jquery object to update + * @param {Array} _array - array of alerts for this member + * @param {jQuery} _count - jQuery object to hold alert count + */ +function toggleAlert(_target, _array, _count) +{ + if (_array.length < 1) + {$(_target).removeClass('on'); $(_target).addClass('off'); } + else {$(_count).empty(); $(_count).append(_array.length); + $(_target).removeClass('off'); $(_target).addClass('on'); } + +} +/** + * check to see if _id is subscribing + * @param {Integer} _id - member id to seek + * @returns {String} - type of member + */ +function getSubscriber(_id) +{ + let type = 'none'; + for (let each in subscribers){(function(_idx, _arr){if (_arr[_idx].id === _id){type=_arr[_idx].type;}})(each, subscribers);} + return(type); +} +/** + * subscribe to events + * @param {String} _type - member type + * @param {String} _id - member id + */ +function z2bSubscribe(_type, _id) +{ + subscribers.push({'type': _type, 'id': _id}); +} +/** + * Unsubscribe to events + * @param {String} _id - member id to remove + */ +function z2bUnSubscribe(_id) +{ + let _s1 = subscribers; + let _s2 = []; + for (let each in _s1) {(function(_idx, _arr){if (_arr[_idx] != _id){_s2.push(_arr[_idx]);}})(each, _s1);} + subscribers = _s2; +} +/** + * notifyMe + * @param {Array} _alerts - array of alerts + * @param {String} _id - orderID + * @returns {Boolean} - true if found, false if not found + */ +function notifyMe (_alerts, _id) +{ + let b_h = false; + for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} + return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter10/HTML/js/z2b-financeCo.js b/Chapter10/HTML/js/z2b-financeCo.js index 64355a0..211b139 100644 --- a/Chapter10/HTML/js/z2b-financeCo.js +++ b/Chapter10/HTML/js/z2b-financeCo.js @@ -19,6 +19,11 @@ let financeCOorderDiv = 'financeCOorderDiv'; let orders = []; const financeCoID = 'easymoney@easymoneyinc.com'; +const financeCoName = 'The Global Financier'; +let f_notify = '#financeCo_notify'; +let f_id = 'easymoney@easymoneyinc.com'; +let f_count = '#financeCo_count'; +let f_alerts; /** * load the finance company User Experience @@ -26,33 +31,34 @@ const financeCoID = 'easymoney@easymoneyinc.com'; function loadFinanceCoUX () { let toLoad = 'financeCo.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupFinanceCo(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupFinanceCo(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupFinanceCo(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupFinanceCo(page);}); } } /** * @param {String} page HTML page to load - * @param {Integer} port Websocket port to use */ -function setupFinanceCo(page, port) +function setupFinanceCo(page) { $('#body').empty(); $('#body').append(page); + f_alerts = []; + if (f_alerts.length === 0) + {$(f_notify).removeClass('on'); $(f_notify).addClass('off'); } + else + {$(f_notify).removeClass('off'); $(f_notify).addClass('on'); } updatePage( 'financeCo'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('finance_messages', msgPort); let _clear = $('#financeCOclear'); let _list = $('#financeCOorderStatus'); let _orderDiv = $('#'+financeCOorderDiv); _clear.on('click', function(){_orderDiv.empty();}); _list.on('click', function(){listFinanceOrders();}); + z2bSubscribe('FinanceCo', f_id); } /** * lists all orders for the selected financier @@ -75,8 +81,8 @@ function listFinanceOrders() * used by the listOrders() function * formats the orders for a financier. Orders to be formatted are provided in the _orders array * output replaces the current contents of the html element identified by _target - * @param _target - string with div id prefaced by # - * @param _orders - array with order objects + * @param {String} _target - string with div id prefaced by # + * @param {Integer} _orders - array with order objects */ function formatFinanceOrders(_target, _orders) { @@ -144,8 +150,10 @@ function formatFinanceOrders(_target, _orders) let _button = '' _action += ''; if (_idx > 0) {_str += '
    ';} - _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    '; - _str += ''+_action+''+_button+'
    Order #StatusTotalBuyer: '+findMember(_arr[_idx].buyer,buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + let _len = 'resource:org.acme.Z2BTestNetwork.Buyer#'.length; + let _buyer = _arr[_idx].buyer.substring(_len, _arr[_idx].buyer.length); + _str += '
    '; + _str += ''+_action+''+_button+'
    Order #StatusTotalBuyer: '+findMember(_buyer,buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; _str+= formatDetail(_idx, _arr[_idx]); })(each, _orders); } @@ -168,11 +176,17 @@ function formatFinanceOrders(_target, _orders) $('#finance_messages').prepend(formatMessage(_results.result)); }); }); + if (notifyMe(f_alerts, _arr[_idx].id)) {$("#f_status"+_idx).addClass('highlight'); } })(each, _orders); } + f_alerts = new Array(); + toggleAlert($('#financeCo_notify'), f_alerts, f_alerts.length); } /** * format the accordian with the details for this order + * @param {Integer} _cur - offset into order array + * @param {JSON} _order - JSON object with current order data + * @returns {String} - html string to append to browser page */ function formatDetail(_cur, _order) { diff --git a/Chapter10/HTML/js/z2b-initiate.js b/Chapter10/HTML/js/z2b-initiate.js index 290ef03..7ba4493 100644 --- a/Chapter10/HTML/js/z2b-initiate.js +++ b/Chapter10/HTML/js/z2b-initiate.js @@ -13,41 +13,52 @@ */ // z2c-initiate.js -var connectionProfileName = "z2b-test-profile"; -var networkFile = "zerotoblockchain-network.bna" -var businessNetwork = "zerotoblockchain-network"; - -var buyers, sellers, providers, shippers; -var s_string, p_string, sh_string; - -var orderStatus = { - Created: {code: 1, text: 'Order Created'}, - Bought: {code: 2, text: 'Order Purchased'}, - Cancelled: {code: 3, text: 'Order Cancelled'}, - Ordered: {code: 4, text: 'Order Submitted to Provider'}, - ShipRequest: {code: 5, text: 'Shipping Requested'}, - Delivered: {code: 6, text: 'Order Delivered'}, - Delivering: {code: 15, text: 'Order being Delivered'}, - Backordered: {code: 7, text: 'Order Backordered'}, - Dispute: {code: 8, text: 'Order Disputed'}, - Resolve: {code: 9, text: 'Order Dispute Resolved'}, - PayRequest: {code: 10, text: 'Payment Requested'}, - Authorize: {code: 11, text: 'Payment Approved'}, - Paid: {code: 14, text: 'Payment Processed'}, - Refund: {code: 12, text: 'Order Refund Requested'}, - Refunded: {code: 13, text: 'Order Refunded'} + +'use strict'; + +let connectionProfileName = 'z2b-test-profile'; +let networkFile = 'zerotoblockchain-network.bna'; +let businessNetwork = 'zerotoblockchain-network'; + +let host_address = window.location.host; + +let buyers = new Array(); +let sellers= new Array(); +let providers= new Array(); +let shippers= new Array(); + +let s_string, p_string, sh_string; + +let orderStatus = { + Created: {code: 1, text: 'Order Created'}, + Bought: {code: 2, text: 'Order Purchased'}, + Cancelled: {code: 3, text: 'Order Cancelled'}, + Ordered: {code: 4, text: 'Order Submitted to Provider'}, + ShipRequest: {code: 5, text: 'Shipping Requested'}, + Delivered: {code: 6, text: 'Order Delivered'}, + Delivering: {code: 15, text: 'Order being Delivered'}, + Backordered: {code: 7, text: 'Order Backordered'}, + Dispute: {code: 8, text: 'Order Disputed'}, + Resolve: {code: 9, text: 'Order Dispute Resolved'}, + PayRequest: {code: 10, text: 'Payment Requested'}, + Authorize: {code: 11, text: 'Payment Approved'}, + Paid: {code: 14, text: 'Payment Processed'}, + Refund: {code: 12, text: 'Order Refund Requested'}, + Refunded: {code: 13, text: 'Order Refunded'} }; /** * standard home page initialization routine * Refer to this by {@link initPage()}. */ - function initPage () +function initPage () { - // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English - goMultiLingual("US_English", "index"); - // singleUX loads the members already present in the network - memberLoad(); - // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring - getChainEvents(); + // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English + goMultiLingual('US_English', 'index'); + // singleUX loads the members already present in the network + memberLoad(); + // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring + getChainEvents(); + // get the asynch port + wsConnect(); } diff --git a/Chapter10/HTML/js/z2b-provider.js b/Chapter10/HTML/js/z2b-provider.js index 99d667f..4a9e800 100644 --- a/Chapter10/HTML/js/z2b-provider.js +++ b/Chapter10/HTML/js/z2b-provider.js @@ -17,6 +17,10 @@ 'use strict'; let providerOrderDiv = 'providerOrderDiv'; +let p_alerts = []; +let p_notify = '#provider_notify'; +let p_count = '#provider_count'; +let p_id; /** * load the Provider User Experience @@ -24,30 +28,28 @@ let providerOrderDiv = 'providerOrderDiv'; function loadProviderUX () { let toLoad = 'provider.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupProvider(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupProvider(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupProvider(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupProvider(page);}); } } /** * load the Provider User Experience * @param {String} page - the name of the page to load - * @param {Integer} port - the port number to use */ -function setupProvider(page, port) +function setupProvider(page) { $('#body').empty(); $('#body').append(page); + if (p_alerts.length === 0) + {$(p_notify).removeClass('on'); $(p_notify).addClass('off'); } + else {$(p_notify).removeClass('off'); $(p_notify).addClass('on'); } updatePage('provider'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('provider_messages', msgPort); let _clear = $('#provider_clear'); let _list = $('#providerOrderStatus'); let _orderDiv = $('#'+providerOrderDiv); @@ -57,9 +59,15 @@ function setupProvider(page, port) $('#provider').append(p_string); $('#providerCompany').empty(); $('#providerCompany').append(providers[0].companyName); + p_id = providers[0].id; + z2bSubscribe('Provider', p_id); + // create a function to execute when the user selects a different provider $('#provider').on('change', function() { $('#providerCompany').empty(); _orderDiv.empty(); $('#provider_messages').empty(); $('#providerCompany').append(findMember($('#provider').find(':selected').val(),providers).companyName); + z2bUnSubscribe(p_id); + p_id = findMember($('#provider').find(':selected').text(),providers).id; + z2bSubscribe('Provider', p_id); }); } /** @@ -137,9 +145,6 @@ function formatProviderOrders(_target, _orders) _action += ''; b_string += '
    '+textPrompts.orderProcess.Refund.prompt+''; break; - case orderStatus.Cancelled.code: - _date = _arr[_idx].cancelled; - break; case orderStatus.Paid.code: _date = _arr[_idx].paid; break; @@ -150,7 +155,7 @@ function formatProviderOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; @@ -143,7 +151,7 @@ function formatShipperOrders(_target, _orders) console.log('shipper _action: '+_action); if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+_statusText+''+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+'Buyer: '+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+_statusText+''+_button+''; _str+= '' for (let every in _arr[_idx].items) {(function(_idx2, _arr2) @@ -173,6 +181,9 @@ function formatShipperOrders(_target, _orders) $('#shipper_messages').prepend(formatMessage(_results.result)); }); }); + if (notifyMe(sh_alerts, _arr[_idx].id)) {$("#sh_status"+_idx).addClass('highlight'); } })(each, _orders); } -} \ No newline at end of file + sh_alerts = new Array(); + toggleAlert($('#shipper_notify'), sh_alerts, sh_alerts.length); + } \ No newline at end of file diff --git a/Chapter10/HTML/js/z2b-utilities.js b/Chapter10/HTML/js/z2b-utilities.js index ae1637f..7f2c962 100644 --- a/Chapter10/HTML/js/z2b-utilities.js +++ b/Chapter10/HTML/js/z2b-utilities.js @@ -6,68 +6,72 @@ * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, + * distributed under the License is distributed on an "AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -// z2c-utilities.js - +// z2c-utilities.js +'use strict'; /** * creates a set of utilities inside the named space: z2c * All utilities are accessed as z2c.functionName() * @namespace - z2c */ -languages = {}, // getSupportedLanguages -selectedLanguage = {}, -language = "", -textLocations = {}, // getTextLocations -textPrompts = {}, // getSelectedPromots +let languages = {}, // getSupportedLanguages + selectedLanguage = {}, + language = '', + textLocations = {}, // getTextLocations + textPrompts = {}, // getSelectedPromots + subscribers = new Array(); // subscribers to business events /** * get the value associated with a cookie named in the input * Refer to this by {@link getCookieValue}. * @param {String} _name - the name of the cookie to find -* @namespace +* @returns {String} - cookie value +* @namespace */ function getCookieValue(_name) { - var name = _name+"="; - var cookie_array= document.cookie.split(";"); - for (each in cookie_array) - { var c = cookie_array[each].trim(); - if(c.indexOf(name) == 0) return(c.substring(name.length, c.length)); - } - return(""); + let name = _name+'='; + let cookie_array= document.cookie.split(';'); + for (let each in cookie_array) + { + let c = cookie_array[each].trim(); + if(c.indexOf(name) === 0) {return(c.substring(name.length, c.length));} + } + return(''); } /** * trims a string by removing all leading and trailing spaces * trims the final period, if it exists, from a string. * Refer to this by {@link trimStrip}. -* @param {String} _string String to be trimmed and stripped of trailing period -* @namespace +* @param {String} _string - String to be trimmed and stripped of trailing period +* @returns {String} - trimmed string +* @namespace */ function trimStrip(_string) { - var str = _string.trim(); - var len = str.length; - if(str.endsWith(".")) {str=str.substring(0,len-1);} - return(str); + let str = _string.trim(); + let len = str.length; + if(str.endsWith('.')) {str=str.substring(0,len-1);} + return(str); } /** * replaces text on an html page based on the anchors and text provided in a JSON textPrompts object * Refer to this by {@link updatePage}. * @param {String} _page - a string representing the name of the html page to be updated -* @namespace +* @namespace */ function updatePage(_page) { - for (each in textPrompts[_page]){(function(_idx, _array) - {$("#"+_idx).empty();$("#"+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} + for (let each in textPrompts[_page]){(function(_idx, _array) + {$('#'+_idx).empty();$('#'+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} } /** @@ -75,7 +79,8 @@ function updatePage(_page) * Refer to this by {@link getDisplaytext}. * @param {String} _page - string representing the name of the html page to be updated * @param {String} _item - string representing the html named item to be updated -* @namespace +* @returns {String} - text to be placed on web page +* @namespace */ function getDisplaytext(_page, _item) {return (textPrompts[_page][_item]);} @@ -85,54 +90,56 @@ function getDisplaytext(_page, _item) * Refer to this by {@link goMultiLingual}. * @param {String} _language - language to be used in this session * @param {String} _page - string representing html page to be updated in the selected language -* @namespace +* @namespace */ function goMultiLingual(_language, _page) { language = _language; - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - {languages = _res; - selectedLanguage = languages[_language]; - var options = {}; options.language = _language; - $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) - {textLocations = _locations; - textPrompts = JSON.parse(_prompts[0]); - updatePage(_page); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + {languages = _res; + selectedLanguage = languages[_language]; + let options = {}; options.language = _language; + $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) + {textLocations = _locations; + textPrompts = JSON.parse(_prompts[0]); + updatePage(_page); + }); + let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • '} + })(each, _res); + } + _choices.append(_str); }); - var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); } /** * get SupportedLanguages returns an html menu object with available languages * Refer to this by {@link getSupportedLanguages}. -* @namespace +* @namespace */ function getSupportedLanguages() { - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - { - languages = _res; console.log(_res); var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + { + languages = _res; console.log(_res); let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • ';} + })(each, _res); + } + _choices.append(_str); + }); } /** * returns a JSON object with the pages and objects which support text replacement * Refer to this by {@link getTextLocations}. -* @namespace +* @namespace */ function getTextLocationsfunction () {$.when($.get('/api/getTextLocations')).done(function(_res){textLocations = _res; console.log(_res); });} @@ -140,38 +147,39 @@ function getTextLocationsfunction () /** * returns a JSON object with the text to be used to update identified pages and objects * Refer to this by {@link getSelectedPrompts}. -* @param {String} _inbound -* @namespace +* @param {String} _inbound - page or object to receive updated text +* @namespace */ function getSelectedPrompts(_inbound) { selectedLanguage=languages[_inbound]; - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); } /** * retrieves the prompts for the requested language from the server * Refer to this by {@link qOnSelectedPrompts}. * @param {String} _inbound - string representing the requested language -* @namespace +* @returns {Promise} - returns promise when selected prompts have been retrieved from server +* @namespace */ function qOnSelectedPrompts(_inbound) { - var d_prompts = $.Deferred(); - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); + return d_prompts.promise(); } /** * function to display the properties of an object using console.log * Refer to this by {@link displayObjectProperties}. * @param {Object} _obj - the object whose properties are to be displayed -* @namespace +* @namespace */ function displayObjectProperties(_obj) { - for(var propt in _obj){ console.log("object property: "+propt ); } + for(let propt in _obj){ console.log('object property: '+propt ); } } /** @@ -179,12 +187,12 @@ function displayObjectProperties(_obj) * Refer to this by {@link displayObjectValues}. * @param {String} _string - an arbitrary string to preface the printing of the object property name and value. often used to display the name of the object being printed * @param {Object} _object - the object to be introspected -* @namespace +* @namespace */ function displayObjectValues(_string, _object) { - for (prop in _object){ - console.log(_string+prop+": "+(((typeof(_object[prop]) == 'object') || (typeof(_object[prop]) == 'function')) ? typeof(_object[prop]) : _object[prop])); + for (let prop in _object){ + console.log(_string+prop+': '+(((typeof(_object[prop]) === 'object') || (typeof(_object[prop]) === 'function')) ? typeof(_object[prop]) : _object[prop])); } } @@ -201,124 +209,126 @@ function displayObjectValues(_string, _object) */ String.prototype.format = function(i, safe, arg) { +/** + * the format function added to String.prototype + * @returns {String} - returns original string with {x} replaced by provided text + */ + function format() { + let str = this, len = arguments.length+1; - function format() { - var str = this, len = arguments.length+1; - - // For each {0} {1} {n...} replace with the argument in that position. If - // the argument is an object or an array it will be stringified to JSON. - for (i=0; i < len; arg = arguments[i++]) { - safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; - str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + // For each {0} {1} {n...} replace with the argument in that position. If + // the argument is an object or an array it will be stringified to JSON. + for (i=0; i < len; arg = arguments[i++]) { + safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; + str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + } + return str; } - return str; - } - // Save a reference of what may already exist under the property native. - // Allows for doing something like: if("".format.native) { /* use native */ } - format.native = String.prototype.format; - - // Replace the prototype property - return format; + // Save a reference of what may already exist under the property native. + // Allows for doing something like: if(''.format.native) { /* use native */ } + format.native = String.prototype.format; + // Replace the prototype property + return format; }(); /** * display the hyperledger apis as currently understood * Refer to this by {@link showAPIDocs}. - * + * */ function showAPIDocs() { - $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) - { - var _target = $("#body"); - _target.empty(); _target.append(_page[0]); - displayAPI(_res[0]); - }); + $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) + { + let _target = $('#body'); + _target.empty(); _target.append(_page[0]); + displayAPI(_res[0]); + }); } /** - * - * @param {JSON} _api + * + * @param {JSON} _api * Refer to this by {@link displayAPI}. - * + * */ function displayAPI(_api) { - var _exports = _api.hfcExports; - var _classes = _api.hfcClasses; - var _eTarget = $("#hfc_exports"); - var _cTarget = $("#hfc_classes"); - var _str = ""; - for (each in _exports) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - _str += ""; - })(each, _exports); - } - _eTarget.append(_str); - _str = ""; - for (each in _classes) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - for (every in _arr[_idx][_curObj[0]]){ - (function(_idx2, _arr2) - { - _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); - _str+= ""; - })(every, _arr[_idx][_curObj[0]]) - } - })(each, _classes); - } - _cTarget.append(_str); + let _exports = _api.hfcExports; + let _classes = _api.hfcClasses; + let _eTarget = $('#hfc_exports'); + let _cTarget = $('#hfc_classes'); + let _str = ''; + for (let each in _exports) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + _str += ''; + })(each, _exports); + } + _eTarget.append(_str); + _str = ''; + for (let each in _classes) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + for (let every in _arr[_idx][_curObj[0]]){ + (function(_idx2, _arr2) + { + let _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); + _str+= ''; + })(every, _arr[_idx][_curObj[0]]); + } + })(each, _classes); + } + _cTarget.append(_str); } /** * format messages for display + * @param {String} _msg - text to be enclosed in html message format + * @returns {String} - html formatted message */ function formatMessage(_msg) {return '

    '+_msg+'

    ';} + /** - * get the web socket port + * closes all accordians in this div + * @param {String} target - formatted jQuery string pointing to div with all accordians to collapse */ -function getPort () +function accOff(target) { - if (msgPort == null) - { $.when($.get('/setup/getPort')).done(function (port){console.log('port is: '+port.port); msgPort = port.port;});} + let thisElement = $(target); + let childNodes = thisElement.children(); + for (let each in childNodes) + {let node = '#'+childNodes[each].id; + if (node !== '#') + { + if($(node).hasClass('on')) {$(node).removeClass('on');} + $(node).addClass('off'); + } + } } + /** * toggle an accordian window + * @param {String} _parent - Div holding all accordians + * @param {String} _body - Div which only appears when accordian is expanded + * @param {HTMLDiv} _header - Div which appears when accordian is collapsed */ function accToggle(_parent, _body, _header) { - var parent = "#"+_parent; - var body="#"+_body; - var header = _header; - if ($(body).hasClass("on")) - {$(body).removeClass("on"); $(body).addClass("off"); - $(parent).removeClass("on"); $(parent).addClass("off"); - }else - { - accOff(parent); - $(body).removeClass("off"); $(body).addClass("on"); - $(parent).removeClass("off"); $(parent).addClass("on"); - } -} -/** - * - */ -function accOff(target) -{ - var thisElement = $(target); - var childNodes = thisElement.children(); - for (each in childNodes) - {var node = "#"+childNodes[each].id; - if (node != '#') - { - if($(node).hasClass("on")) {$(node).removeClass("on");} - $(node).addClass("off"); - } - } + let parent = '#'+_parent; + let body='#'+_body; + if ($(body).hasClass('on')) + { + $(body).removeClass('on'); $(body).addClass('off'); + $(parent).removeClass('on'); $(parent).addClass('off'); + }else + { + accOff(parent); + $(body).removeClass('off'); $(body).addClass('on'); + $(parent).removeClass('off'); $(parent).addClass('on'); + } } diff --git a/Chapter10/controller/restapi/features/composer/Z2B_Services.js b/Chapter10/controller/restapi/features/composer/Z2B_Services.js index 21dbb85..c4f8aa4 100644 --- a/Chapter10/controller/restapi/features/composer/Z2B_Services.js +++ b/Chapter10/controller/restapi/features/composer/Z2B_Services.js @@ -13,16 +13,18 @@ */ 'use strict'; -var fs = require('fs'); -var path = require('path'); +let fs = require('fs'); +let path = require('path'); const sleep = require('sleep'); -const ws = require('websocket'); -const http = require('http'); +// const ws = require('websocket'); +// const http = require('http'); +// const url = require('url'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); const appEnv = cfenv.getAppEnv(); +const util = require('./Z2B_Utilities'); app.set('port', appEnv.port); @@ -37,7 +39,7 @@ app.set('port', appEnv.port); * @class * @memberof module:Z2Blockchain */ -var Z2Blockchain = { +let Z2Blockchain = { /** * create an empty order. This is used by any server side routine that needs to create an new @@ -105,8 +107,8 @@ var Z2Blockchain = { /** * update item quantity. used by the autoLoad process. * @param {item_number} _itemNo - item number to find - * @param {vendor_array} _itemArray - item array from order * @param {item_number} _qty - quantity to change * @utility + * @param {vendor_array} _itemArray - item array from order */ setItem: function (_itemNo, _qty, _itemArray) { @@ -115,46 +117,78 @@ var Z2Blockchain = { }, /** * supplemental routine to resubmit orders when MVCC_READ_CONFLICT encountered + * @param {object} _con - web socket connection * @param {transaction} _item - transaction to process * @param {order_object} _id - order id - * @param {bnc} businessNetworkConnection - already created business network connection + * @param {BusinessNetworkConnection} businessNetworkConnection - already created business network connection + * @returns {promise} promise */ loadTransaction: function (_con, _item, _id, businessNetworkConnection) { + let method = 'loadTransaction'; return businessNetworkConnection.submitTransaction(_item) .then(() => { - console.log('loadTransaction: order '+_id+' successfully added'); - _con.sendUTF('loadTransaction: order '+_id+' successfully added'); + console.log(method+': order '+_id+' successfully added '); + this.send(_con, 'Message', 'Order '+_id+' successfully added'); }) .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) + if (error.message.search('MVCC_READ_CONFLICT') !== -1) {sleep.sleep(5); - console.log(_id+" loadTransaction retrying submit transaction for: "+_id); - this.loadTransaction(_con,_item, _id, businessNetworkConnection); + console.log(_id+' loadTransaction retrying submit transaction for: '+_id); + this.loadTransaction(_con, _item, _id, businessNetworkConnection); } }); }, /** * add an order to a registry. This adds an Asset and does not execute a transaction - * @param {order_object} _order - order_object to process - * @param {assetRegistry} _registry - registry into which asset (order) should be placed + * @param {order_object} _con - websocket + * @param {assetRegistry} _order - order_object to process + * @param {networkTransaction} _registry - registry into which asset (order) should be placed * @param {networkTransaction} _createNew - transaction to be processed after order successfully added - * @param {businessNetworkConnection} _bnc - business network connection to use */ - addOrder: function (_con, _order, _registry, _createNew, _bnc) - { - return _registry.add(_order) - .then(() => { - this.loadTransaction(_con,_createNew, _order.orderNumber, _bnc); - }) - .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) - {console.log(_order.orderNumber+" addOrder retrying assetRegistry.add for: "+_order.orderNumber); - this.addOrder(_con,_order, _registry, _createNew, _bnc); - } - else {console.log('error with assetRegistry.add', error)} - }); + * @param {businessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +addOrder: function (_con, _order, _registry, _createNew, _bnc) +{ + let method = 'addOrder'; + return _registry.add(_order) + .then(() => { + this.loadTransaction(_con, _createNew, _order.orderNumber, _bnc); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(_order.orderNumber+' addOrder retrying assetRegistry.add for: '+_order.orderNumber); + this.addOrder(_con, _order, _registry, _createNew, _bnc); + } + else {console.log(method+' error with assetRegistry.add', error);} + }); }, +/** + * repeats the bind identity request + * @param {WebSocket} _con - order_object to process + * @param {String} _id - registry into which asset (order) should be placed + * @param {String} _cert - transaction to be processed after order successfully added + * @param {BusinessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +bindIdentity: function (_con, _id, _cert, _bnc) +{ + let method = 'bindIdentity'; + console.log(method+' retrying bindIdentity for: '+_id); + return _bnc.bindIdentity(_id, _cert) + .then(() => { + console.log(method+' Succeeded for: '+_id); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(' bindIdentity retrying _bnc.bindIdentity(_id, _cert) for: '+_id); + this.bindIdentity(_con, _id, _cert, _bnc); + } + else {console.log(method+' error with _bnc.bindIdentity(_id, _cert) for: '+_id+' with error: ', error);} + }); +}, + /** * saves the member table with ids and secrets * @param {array} _table - array of JSON objects to save to file @@ -166,23 +200,26 @@ var Z2Blockchain = { let _mem = '{"members": ['; for (let each in _table) {(function(_idx, _arr) - {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table)} + {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table);} _mem += ']}'; fs.writeFileSync(newFile, _mem, options); }, /** * saves the item table * @param {array} _table - array of JSON objects to save to file + * @param {JSON} _table - data to be saved */ - saveItemTable: function (_table) - { - let options = { flag : 'w' }; - let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); - let _mem = '{"items": ['; - for (let each in _table) - {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table)} - _mem += ']}'; - fs.writeFileSync(newFile, _mem, options); - }, +saveItemTable: function (_table) +{ + console.log('_table: ', _table); + let options = { flag : 'w' }; + let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); + let _mem = '{"items": ['; + for (let each in _table) + {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table);} + _mem += ']}'; + console.log('_mem: ', _mem); + fs.writeFileSync(newFile, _mem, options); +}, /** * update an empty order with 4 items. update the amount field based on the sum of the line items * @param {addItems} _inbound - Order created with factory.newResource(NS, 'Order',.orderNumber) @@ -205,7 +242,7 @@ var Z2Blockchain = { _arr[_idx].extendedPrice = _item.unitPrice*_arr[_idx].quantity; _amount += _arr[_idx].extendedPrice; _items.push(JSON.stringify(_arr[_idx])); - })(each, _inbound.items)} + })(each, _inbound.items);} return ({'items': _items, 'amount': _amount}); }, /** @@ -213,22 +250,23 @@ var Z2Blockchain = { * was not initially working. This function is no longer in use. * @param {Order} _order - the inbound Order item retrieved from a registry * @return JSON object order elements + * @return {Order} JSON object order elements * @function */ - getOrderData: function (_order) - { - let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', - 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; - var _obj = {}; - for (let each in orderElements){(function(_idx, _arr) - { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements)} - _obj.buyer = _order.buyer.$identifier; - _obj.seller = _order.seller.$identifier; - _obj.provider = _order.seller.$provider; - _obj.shipper = _order.seller.$shipper; - _obj.financeCo = _order.seller.$financeCo; - return (_obj); - }, +getOrderData: function (_order) +{ + let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', + 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; + let _obj = {}; + for (let each in orderElements){(function(_idx, _arr) + { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements);} + _obj.buyer = _order.buyer.$identifier; + _obj.seller = _order.seller.$identifier; + _obj.provider = _order.seller.$provider; + _obj.shipper = _order.seller.$shipper; + _obj.financeCo = _order.seller.$financeCo; + return (_obj); +}, /** * JSON object of available order status types and codes. This is used by nodejs @@ -252,67 +290,15 @@ var Z2Blockchain = { Refunded: {code: 13, text: 'Order Refunded'} }, /** - * the user experience is enhanced if the browser can be notified of aysnchronous events. - * the createMessateSockt function creates a web socket service to which the browser can - * attach. - * @param {integer} _port - port number to use for this socket connection - * @returns {websocket} - web socket connection to be used on the server side. - */ - m_connection: null, - m_socketAddr: null, - m_socket: null, - createMessageSocket: function (_port) - { - var port = (typeof(_port) == 'undefined' || _port == null) ? app.get('port')+1 : _port - if (this.m_socket == null) - { - this.m_socketAddr = port; - this.m_socket= new ws.server({httpServer: http.createServer().listen(this.m_socketAddr)}); - var _this = this; - this.m_socket.on('request', function(request) - { - _this.m_connection = request.accept(null, request.origin); - _this.m_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.m_connection.sendUTF('connected'); - _this.m_connection.on('close', function(m_connection) {console.log('m_connection closed'); }); - }); - }); - } - return {conn: this.m_connection, socket: this.m_socketAddr}; - }, -/** - * the cs_connection is used to display blockchain information to the web browser over - * a sepaarate port from the user experience socket. - * @returns {websocket} - web socket connection to be used on the server side. + * New code to support sending messages to socket clients + * @param {Object} _locals - shared variables and functions from index.js + * @param {String} type - type of event message to put on channel + * @param {Event} event - event message */ - - cs_connection: null, - cs_socketAddr: null, - cs_socket: null, - createChainSocket: function () - { - var port = app.get('port')+2; - if (this.cs_socket == null) - { - this.cs_socketAddr = port; - this.cs_socket= new ws.server({httpServer: http.createServer().listen(this.cs_socketAddr)}); - var _this = this; - this.cs_socket.on('request', function(request) - { - _this.cs_connection = request.accept(null, request.origin); - _this.cs_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.cs_connection.sendUTF('connected'); - _this.cs_connection.on('close', function(cs_connection) {console.log('cs_connection closed'); }); - }); - }); - } - return {conn: this.cs_connection, socket: this.cs_socketAddr}; - } - +send: function (_locals, type, event) +{ + _locals.processMessages({'type': type, 'data': event} ); } +}; module.exports = Z2Blockchain; \ No newline at end of file diff --git a/Chapter10/controller/restapi/features/composer/autoLoad.js b/Chapter10/controller/restapi/features/composer/autoLoad.js index ce3d81b..da256aa 100644 --- a/Chapter10/controller/restapi/features/composer/autoLoad.js +++ b/Chapter10/controller/restapi/features/composer/autoLoad.js @@ -34,32 +34,13 @@ const financeCoID = 'easymoney@easymoneyinc.com'; const svc = require('./Z2B_Services'); const config = require('../../../env.json'); + /** * itemTable and memberTable are used by the server to reduce load time requests * for member secrets and item information */ let itemTable = new Array(); let memberTable = new Array(); -let socketAddr; - - - - - -/** - * getPort is used to return the port number for socket interactions so that - * the browser can receive asynchronous notifications of work in process. - * This helps the user understand the current status of the auto load process. - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * - * @function - */ -exports.getPort = function(req, res, next) { - let _conn = svc.createMessageSocket(); - res.send({'port': _conn.socket}); -}; /** * autoLoad reads the memberList.json file from the Startup folder and adds members, @@ -78,9 +59,9 @@ exports.autoLoad = function(req, res, next) { // connect to the network let businessNetworkConnection; let factory; let participant; - svc.createMessageSocket(); - socketAddr = svc.m_socketAddr; - let adminConnection = new AdminConnection(); +// svc.createMessageSocket(); +// socketAddr = svc.m_socketAddr; +let adminConnection = new AdminConnection(); // connection prior to V0.15 // adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW) // connection in v0.15 @@ -110,7 +91,7 @@ exports.autoLoad = function(req, res, next) { return participantRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { participant = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); @@ -118,7 +99,7 @@ exports.autoLoad = function(req, res, next) { participantRegistry.add(participant) .then(() => { console.log('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); - svc.m_connection.sendUTF('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); + svc.send(req.app.locals, 'Message', '['+_idx+'] '+_arr[_idx].companyName+' successfully added'); }) .then(() => { // an identity is required before a member can take action in the network. @@ -144,7 +125,9 @@ exports.autoLoad = function(req, res, next) { config.connectionProfile.keyValStore = _home+config.connectionProfile.keyValStore; let tempCard = new hlc_idCard(_meta, config.connectionProfile); return adminConnection.importCard(result.userID, tempCard) - .then ((_res) => { if (_res) {console.log('card updated');} else {console.log('card imported');} }) + .then ((_res) => { + if (_res) {console.log('card updated');} else {console.log('card imported');} + }) .catch((error) => { console.error('adminConnection.importCard failed. ',error.message); }); @@ -172,7 +155,7 @@ exports.autoLoad = function(req, res, next) { return assetRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { // first, an Order Object is created @@ -186,8 +169,8 @@ exports.autoLoad = function(req, res, next) { const createNew = factory.newTransaction(config.composer.NS, 'CreateOrder'); order.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); order.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); - order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummy'); - order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummy'); + order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummyProvider'); + order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummyShipper'); order.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.order = factory.newRelationship(config.composer.NS, 'Order', order.$identifier); @@ -199,7 +182,7 @@ exports.autoLoad = function(req, res, next) { .then(() => { // then a createOrder transaction is processed which uses the chaincode // establish the order with it's initial transaction state. - svc.loadTransaction(svc.m_connection, createNew, order.orderNumber, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, order.orderNumber, businessNetworkConnection); }) .catch((error) => { // in the development environment, because of how timing is set up, it is normal to @@ -207,8 +190,8 @@ exports.autoLoad = function(req, res, next) { // logical transaction error. if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log('AL: '+_arr[_idx].id+' retrying assetRegistry.add for: '+_arr[_idx].id); - svc.addOrder(svc.m_connection, order, assetRegistry, createNew, businessNetworkConnection); - } + svc.addOrder(req.app.locals, order, assetRegistry, createNew, businessNetworkConnection); + } else {console.log('error with assetRegistry.add', error.message);} }); }); @@ -220,7 +203,7 @@ exports.autoLoad = function(req, res, next) { .catch((error) => {console.log('error with business network Connect', error.message);}); }) .catch((error) => {console.log('error with adminConnect', error.message);}); - res.send({'port': socketAddr}); + res.send({'result': 'Success'}); }; /** diff --git a/Chapter10/controller/restapi/features/composer/hlcAdmin.js b/Chapter10/controller/restapi/features/composer/hlcAdmin.js index 8e9e8b9..46b188c 100644 --- a/Chapter10/controller/restapi/features/composer/hlcAdmin.js +++ b/Chapter10/controller/restapi/features/composer/hlcAdmin.js @@ -24,8 +24,7 @@ const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefi const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; -// const svc = require('./Z2B_Services'); -// const mod = 'hlcAdmin.js'; + /** * display the admin and network info diff --git a/Chapter10/controller/restapi/features/composer/queryBlockChain.js b/Chapter10/controller/restapi/features/composer/queryBlockChain.js index 9b6a396..75b67d3 100644 --- a/Chapter10/controller/restapi/features/composer/queryBlockChain.js +++ b/Chapter10/controller/restapi/features/composer/queryBlockChain.js @@ -12,8 +12,9 @@ * limitations under the License. */ -var path = require('path'); -var fs = require('fs'); +'use strict'; +let path = require('path'); +let fs = require('fs'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); @@ -24,10 +25,10 @@ const hfc = require('fabric-client'); const hfcEH = require('fabric-client/lib/EventHub'); const svc = require('./Z2B_Services'); -const util = require('./Z2B_Utilities'); -const financeCoID = 'easymoney@easymoneyinc.com'; +// const util = require('./Z2B_Utilities'); +// const financeCoID = 'easymoney@easymoneyinc.com'; const config = require('../../../env.json'); -var chainEvents = false; +let chainEvents = false; @@ -38,11 +39,13 @@ var chainEvents = false; * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainInfo = function(req, res, next) { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); - console.log(wallet_path); +exports.getChainInfo = function(req, res, next) +{ + let method='getChainInfo'; + let HOST_NAME = req.headers.host; + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); Promise.resolve().then(() => { // // As of 9/28/2017 there is a known and unresolved bug in HyperLedger Fabric @@ -61,29 +64,43 @@ exports.getChainInfo = function(req, res, next) { // change PeerAdmin in following line to adminID return client.getUserContext(config.composer.PeerAdmin, true);}) .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + if (user === null || user === undefined || user.isEnrolled() === false) + { console.error('User not defined, or not enrolled - error');} + if (HOST_NAME.slice(0,9) === 'localhost') + { + console.log(method+" running locally"); channel = client.newChannel(config.fabric.channelName); channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - }) + }else + { + console.log(method+" running remotely, not supported in Chapter 12"); + } + }) .then(() => { return channel.queryInfo() .then((blockchainInfo) => { if (blockchainInfo) { - res.send({"result": "success", "currentHash": blockchainInfo.currentBlockHash.toString("hex"), blockchain: blockchainInfo}); + res.send({'result': 'success', 'currentHash': blockchainInfo.currentBlockHash.toString('hex'), blockchain: blockchainInfo}); } else { console.log('response_payload is null'); - res.send({"result": "uncertain", "message": 'response_payload is null'}); + res.send({'result': 'uncertain', 'message': 'response_payload is null'}); } }) .catch((_err) => { - console.log("queryInfo failed with _err = ", _err); - res.send({"result": "failed", "message": _err.message}); - }); + console.log('queryInfo failed with _err = ', _err); + res.send({'result': 'failed', 'message': _err.message}); + }); }); - }); -} + }); +}; /** * get chain events @@ -92,37 +109,55 @@ exports.getChainInfo = function(req, res, next) { * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainEvents = function(req, res, next) { +exports.getChainEvents = function(req, res, next) +{ + let method = 'getChainEvents'; + let HOST_NAME = req.headers.host; if (chainEvents) {res.send({'port': svc.cs_socketAddr});} else { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); + Promise.resolve().then(() => { client = new hfc(); return hfc.newDefaultKeyValueStore({ path: wallet_path }) .then((wallet) => { client.setStateStore(wallet); // change PeerAdmin in following line to adminID - return client.getUserContext(config.composer.PeerAdmin, true);}) - .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} - channel = client.newChannel(config.fabric.channelName); - channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); - channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - // change Admin in following line to admin - var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); - var adminPEM = fs.readFileSync(pemPath).toString(); - var bcEvents = new hfcEH(client); - bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + return client.getUserContext(config.composer.PeerAdmin, true); + }) + .then((user) => { + if (user === null || user === undefined || user.isEnrolled() === false) + {console.error(method+': User not defined, or not enrolled - error');} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + // get the channel name + channel = client.newChannel(config.fabric.channelName); + //get the request URL for the Peer0 container + channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); + // get the orderer URL + channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); + // change Admin in following line to admin + var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); + var adminPEM = fs.readFileSync(pemPath).toString(); + var bcEvents = new hfcEH(client); + bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + bcEvents.registerBlockEvent( + function(event){svc.send(req.app.locals, 'BlockChain', event);}, + function(error){console.log(method+': registerBlockEvent error: ', error);} + ); bcEvents.connect(); - svc.createChainSocket(); - bcEvents.registerBlockEvent(function(event) {svc.cs_connection.sendUTF(JSON.stringify(event));}); - chainEvents = true; - res.send({'port': svc.cs_socketAddr}); - }) - }); - } -} + chainEvents = true; + res.send({'port': svc.cs_socketAddr}); + }) + .catch((err) => { console.log(method+': getUserContext failed: ',err);}); + }); + } +}; diff --git a/Chapter10/controller/restapi/router.js b/Chapter10/controller/restapi/router.js index 6fa15bd..14883e7 100644 --- a/Chapter10/controller/restapi/router.js +++ b/Chapter10/controller/restapi/router.js @@ -25,13 +25,15 @@ let hlcAdmin = require('./features/composer/hlcAdmin'); let hlcClient = require('./features/composer/hlcClient'); let setup = require('./features/composer/autoLoad'); let hlcFabric = require('./features/composer/queryBlockChain'); -router.post('/setup/autoLoad*', setup.autoLoad); -router.get('/setup/getPort*', setup.getPort); + router.get('/fabric/getChainInfo', hlcFabric.getChainInfo); router.get('/fabric/getChainEvents', hlcFabric.getChainEvents); router.get('/fabric/getHistory', hlcAdmin.getHistory); +router.post('/setup/autoLoad*', setup.autoLoad); +router.get('/composer/client/initEventRegistry*', hlcClient.init_z2bEvents); + module.exports = router; let count = 0; /** @@ -71,6 +73,7 @@ router.get('/composer/admin/getAllProfiles*', hlcAdmin.getAllProfiles); router.get('/composer/admin/listAsAdmin*', hlcAdmin.listAsAdmin); router.get('/composer/admin/getRegistries*', hlcAdmin.getRegistries); + router.post('/composer/admin/createProfile*', hlcAdmin.createProfile); router.post('/composer/admin/deleteProfile*', hlcAdmin.deleteProfile); router.post('/composer/admin/deploy*', hlcAdmin.deploy); @@ -90,6 +93,7 @@ router.post('/composer/admin/checkCard*', hlcAdmin.checkCard); router.post('/composer/admin/createCard*', hlcAdmin.createCard); router.post('/composer/admin/issueIdentity*', hlcAdmin.issueIdentity); + // router requests specific to the Buyer router.get('/composer/client/getItemTable*', hlcClient.getItemTable); router.post('/composer/client/getMyOrders*', hlcClient.getMyOrders); diff --git a/Chapter10/favicon.ico b/Chapter10/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter10/favicon.ico and /dev/null differ diff --git a/Chapter10/index.js b/Chapter10/index.js index 70319d6..cf79cb7 100644 --- a/Chapter10/index.js +++ b/Chapter10/index.js @@ -14,25 +14,28 @@ /* * Zero to Blockchain */ -var express = require('express'); -var http = require('http'); -var https = require('https'); -var path = require('path'); -var fs = require('fs'); -var mime = require('mime'); -var bodyParser = require('body-parser'); -var cfenv = require('cfenv'); -var cookieParser = require('cookie-parser'); -var session = require('express-session'); +'use strict'; +const express = require('express'); +const http = require('http'); +const ws = require('websocket').server; +// const https = require('https'); +const path = require('path'); +const fs = require('fs'); +const mime = require('mime'); +const bodyParser = require('body-parser'); +const cfenv = require('cfenv'); -var vcapServices = require('vcap_services'); -var uuid = require('uuid'); -var env = require('./controller/envV2.json'); -var sessionSecret = env.sessionSecret; -var appEnv = cfenv.getAppEnv(); -var app = express(); -var busboy = require('connect-busboy'); +const cookieParser = require('cookie-parser'); +// const session = require('express-session'); + +// const vcapServices = require('vcap_services'); +// const uuid = require('uuid'); +const env = require('./controller/envV2.json'); +const sessionSecret = env.sessionSecret; +const appEnv = cfenv.getAppEnv(); +const app = express(); +const busboy = require('connect-busboy'); app.use(busboy()); // the session secret is a text string of arbitrary length which is @@ -49,7 +52,8 @@ app.use(cookieParser(sessionSecret)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); -app.set('appName', 'z2b-chapter07'); +app.set('appName', 'z2b-chapter12'); +process.title = 'Z2B-C12'; app.set('port', appEnv.port); app.set('views', path.join(__dirname + '/HTML')); @@ -59,14 +63,58 @@ app.use(express.static(__dirname + '/HTML')); app.use(bodyParser.json()); // Define your own router file in controller folder, export the router, add it into the index.js. -// app.use('/', require("./controller/yourOwnRouter")); -app.use('/', require("./controller/restapi/router")); +app.use('/', require('./controller/restapi/router')); + +let server = http.createServer(); +let clients = []; +app.locals.index=-1; +/** + * WebSocket server + */ +app.locals.wsServer = new ws({httpServer: server}); +app.locals.wsServer.on('request', function(request) +{ + // create a connection back to the requestor + app.locals.connection = request.accept(null, request.origin); + // we need to know client index to remove them on 'close' event + app.locals.index = clients.push(app.locals.connection) - 1; + // save the newly created connection. This is so that we can support many connections to many browsers simultaneously + console.log((new Date()) + ' Connection accepted.'); + app.locals.connection.on('message', function(message) + { let obj ={ime: (new Date()).getTime(),text: message.utf8Data}; + // broadcast message to all connected clients + let json = JSON.stringify({ type:'Message', data: obj }); + app.locals.processMessages(json); + }); + + // user disconnected + app.locals.connection.on('close', function(_conn) { + console.log((new Date()) + ' Peer '+ app.locals.connection.socket._peername.address+':'+app.locals.connection.socket._peername.port+' disconnected with reason code: "'+_conn+'".'); + // remove user from the list of connected clients + // each browser connection has a unique address and socket combination + // When a browser session is disconnected, remove it from the array so we don't waste processing time sending messages to empty queues. + for (let each in clients) + {(function(_idx, _arr) + {if ((_arr[_idx].socket._peername.address === app.locals.connection.socket._peername.address) && (_arr[_idx].socket._peername.port === app.locals.connection.socket._peername.port)) + {clients.splice(_idx, 1);} + })(each, clients);} + }); +}); -if (cfenv.getAppEnv().isLocal == true) - { var server = app.listen(app.get('port'), function() {console.log('Listening locally on port %d', server.address().port);}); } - else - { var server = app.listen(app.get('port'), function() {console.log('Listening remotely on port %d', server.address().port);}); } +/** + * callable function to send messages over web socket + * @param {JSON} _jsonMsg - json formatted content to be sent as message data + */ +function processMessages (_jsonMsg) +{ + for (let i=0; i < clients.length; i++) {clients[i].send(JSON.stringify(_jsonMsg));} +} +// make the processMessages function available to all modules in this app. +app.locals.processMessages = processMessages; +// now set up the http server +server.on( 'request', app ); +server.listen(appEnv.port, function() {console.log('Listening locally on port %d', server.address().port);}); /** * load any file requested on the server * @param {express.req} req - the inbound request object from the client @@ -74,16 +122,16 @@ if (cfenv.getAppEnv().isLocal == true) * @function */ function loadSelectedFile(req, res) { - var uri = req.originalUrl; - var filename = __dirname + "/HTML" + uri; + let uri = req.originalUrl; + let filename = __dirname + '/HTML' + uri; fs.readFile(filename, function(err, data) { if (err) { console.log('Error loading ' + filename + ' error: ' + err); return res.status(500).send('Error loading ' + filename); } - var type = mime.lookup(filename); - res.setHeader('content-type', type); + let type = mime.lookup(filename); + res.setHeader('content-type', type); res.writeHead(200); res.end(data); }); diff --git a/Chapter10/network/lib/sample.js b/Chapter10/network/lib/sample.js index ddb951a..0d948b6 100644 --- a/Chapter10/network/lib/sample.js +++ b/Chapter10/network/lib/sample.js @@ -104,7 +104,7 @@ function OrderFromSupplier(purchase) { * @transaction */ function RequestShipping(purchase) { - if (purchase.order.status == JSON.stringify(orderStatus.Ordered)) + if ((purchase.order.status == JSON.stringify(orderStatus.Ordered)) || (purchase.order.status == JSON.stringify(orderStatus.Backordered))) { purchase.order.shipper = purchase.shipper; purchase.order.requestShipment = new Date().toISOString(); @@ -159,11 +159,11 @@ function RequestPayment(purchase) { {purchase.order.status = JSON.stringify(orderStatus.PayRequest); purchase.order.financeCo = purchase.financeCo; purchase.order.paymentRequested = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -174,11 +174,11 @@ function AuthorizePayment(purchase) { if ((JSON.parse(purchase.order.status).text == orderStatus.PayRequest.text ) || (JSON.parse(purchase.order.status).text == orderStatus.Resolve.text )) {purchase.order.status = JSON.stringify(orderStatus.Authorize); purchase.order.approved = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -189,11 +189,11 @@ function Pay(purchase) { if (JSON.parse(purchase.order.status).text == orderStatus.Authorize.text ) {purchase.order.status = JSON.stringify(orderStatus.Paid); purchase.order.paid = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a dispute by the buyer diff --git a/Chapter11/Documentation/answers/js/z2b-events_complete.js b/Chapter11/Documentation/answers/js/z2b-events_complete.js index 7b22165..282f3ea 100644 --- a/Chapter11/Documentation/answers/js/z2b-events_complete.js +++ b/Chapter11/Documentation/answers/js/z2b-events_complete.js @@ -16,6 +16,8 @@ 'use strict'; +let wsSocket; + /** * load the four initial user roles into a single page. */ @@ -23,15 +25,16 @@ function singleUX () { let toLoad = 'singleUX.html'; if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (_page, _port, _res) - { - msgPort = _port.port; + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { $('#body').empty(); $('#body').append(_page); loadBuyerUX(); loadSellerUX(); loadProviderUX(); loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); }); } else{ @@ -43,6 +46,8 @@ function singleUX () loadSellerUX(); loadProviderUX(); loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); }); } } @@ -63,15 +68,26 @@ function memberLoad () $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members; - p_string = _getMembers(providers); - shippers = _shippers[0].members; - sh_string = _getMembers(shippers); + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + }); } +/** + * dropDummy() removes 'noop@dummy' from memberlist + * @param {String} _in - member id to ignore + */ +function dropDummy(_in) +{ + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} + return _a; +} /** * load all of the members in the network for use in the different user experiences. This routine is designed for use if the network has been newly deployed and the web app was * started before the autoLoad function was run on the newly deployed network (which, by default, is empty). @@ -90,27 +106,178 @@ function deferredMemberLoad() $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) { - buyers = _buyers[0].members; - sellers = _sellers[0].members; + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); s_string = _getMembers(sellers); - providers = _providers[0].members; p_string = _getMembers(providers); - shippers = _shippers[0].members; sh_string = _getMembers(shippers); d_prompts.resolve(); }).fail(d_prompts.reject); - return d_prompts.promise(); + return d_prompts.promise(); } /** * return an option list for use in an HTML '; return _str; +} +/** + * set up the server to listen for all events + */ +function goEventInitialize() +{ + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); +} + +/** + * @param {Event} _event - inbound Event + * @param {String} _id - subscriber target + * @param {String} _orderID - inbound order id + */ +function addNotification(_event, _id, _orderID) +{ + let method = 'addNotification'; + console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); + let type = getSubscriber(_id); + if (type === 'none') {return;} + switch(type) + { + case 'Buyer': + b_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(b_notify, b_alerts, b_count); + break; + case 'Seller': + s_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(s_notify, s_alerts, s_count); + break; + case 'Provider': + p_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(p_notify, p_alerts, p_count); + break; + case 'Shipper': + sh_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(sh_notify, sh_alerts, sh_count); + break; + case 'FinanceCo': + f_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(f_notify, f_alerts, f_count); + break; + default: + console.log(method+' default entered for: '+type); + break; + } +} +/** + * + * @param {jQuery} _target - jquery object to update + * @param {Array} _array - array of alerts for this member + * @param {jQuery} _count - jQuery object to hold alert count + */ +function toggleAlert(_target, _array, _count) +{ + if (_array.length < 1) + {$(_target).removeClass('on'); $(_target).addClass('off'); } + else {$(_count).empty(); $(_count).append(_array.length); + $(_target).removeClass('off'); $(_target).addClass('on'); } + +} +/** + * check to see if _id is subscribing + * @param {Integer} _id - member id to seek + * @returns {String} - type of member + */ +function getSubscriber(_id) +{ + let type = 'none'; + for (let each in subscribers){(function(_idx, _arr){if (_arr[_idx].id === _id){type=_arr[_idx].type;}})(each, subscribers);} + return(type); +} +/** + * subscribe to events + * @param {String} _type - member type + * @param {String} _id - member id + */ +function z2bSubscribe(_type, _id) +{ + subscribers.push({'type': _type, 'id': _id}); +} +/** + * Unsubscribe to events + * @param {String} _id - member id to remove + */ +function z2bUnSubscribe(_id) +{ + let _s1 = subscribers; + let _s2 = []; + for (let each in _s1) {(function(_idx, _arr){if (_arr[_idx] != _id){_s2.push(_arr[_idx]);}})(each, _s1);} + subscribers = _s2; +} +/** + * notifyMe + * @param {Array} _alerts - array of alerts + * @param {String} _id - orderID + * @returns {Boolean} - true if found, false if not found + */ +function notifyMe (_alerts, _id) +{ + let b_h = false; + for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} + return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter11/HTML/favicon.ico b/Chapter11/HTML/favicon.ico old mode 100755 new mode 100644 index fc9e25d..3dbe425 Binary files a/Chapter11/HTML/favicon.ico and b/Chapter11/HTML/favicon.ico differ diff --git a/Chapter11/HTML/js/z2b-admin.js b/Chapter11/HTML/js/z2b-admin.js index 67f421a..f3c3ffc 100644 --- a/Chapter11/HTML/js/z2b-admin.js +++ b/Chapter11/HTML/js/z2b-admin.js @@ -18,7 +18,6 @@ let creds; let connection; -let msgPort = null; let _blctr = 0; /** @@ -34,19 +33,6 @@ function loadAdminUX () listMemRegistries(); }); } -/** - * connect to the provided web socket - * @param {String} _target - location to post messages - * @param {Integer} _port - web socket port # - */ -function wsDisplay(_target, _port) -{ - let content = $('#'+_target); - let wsSocket = new WebSocket('ws://localhost:'+_port); - wsSocket.onopen = function () {wsSocket.send('connected to client');}; - wsSocket.onmessage = function (message) {content.append(formatMessage(message.data));}; - wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ' + error);}; -} /** * list the available business networks */ @@ -361,7 +347,7 @@ function preLoad() $('#body').empty(); let options = {}; $.when($.post('/setup/autoLoad', options)).done(function (_results) - { msgPort = _results.port; wsDisplay('body', msgPort); }); + { console.log('Autoload Initiated'); $('#body').append('

    Autoload Initiated

    '); }); } /** @@ -754,28 +740,9 @@ function getHistorian() */ function getChainEvents() { - $.when($.get('fabric/getChainEvents')).done(function(_res) - { let _str = '

    Get Chain events requested. Sending to port: '+_res.port+'

    '; - let content = $('#blockchain'); - let csSocket = new WebSocket('ws://localhost:'+_res.port); - csSocket.onopen = function () {csSocket.send('connected to client');}; - csSocket.onmessage = function (message) { - _blctr ++; - if (message.data !== 'connected') - {$(content).append('block '+JSON.parse(message.data).header.number+'
    Hash: '+JSON.parse(message.data).header.data_hash+'
    '); - if (_blctr > 4) {let leftPos = $(content).scrollLeft(); $(content).animate({scrollLeft: leftPos + 300}, 250);} - } - }; - csSocket.onerror = function (error) {console.log('WebSocket error: ' + error);}; - $('#admin-forms').empty(); - $('#admin-forms').append(_str); + $.when($.get('/fabric/getChainEvents')).done(function(_res) + { $('#body').append('

    Get Chain events requested.

    '); + let _host = (host_address.slice(0,9) === 'localhost') ? 'localhost' : host_address; + console.log('getChainEvents host_address: '+_host); }); -} -/** - * display blockchain updates - */ -function displayAdminUpdate() -{ - let toLoad = 'adminHelp.html'; - $.when($.get(toLoad)).done(function(_page){$('#admin-forms').empty(); $('#admin-forms').append(_page);}); } \ No newline at end of file diff --git a/Chapter11/HTML/js/z2b-buyer.js b/Chapter11/HTML/js/z2b-buyer.js index 29b99c0..793ff73 100644 --- a/Chapter11/HTML/js/z2b-buyer.js +++ b/Chapter11/HTML/js/z2b-buyer.js @@ -15,6 +15,10 @@ // z2c-buyer.js 'use strict'; +let b_notify = '#buyer_notify'; +let b_count = '#buyer_count'; +let b_id = ''; +let b_alerts; let orderDiv = 'orderDiv'; let itemTable = {}; @@ -28,31 +32,32 @@ function loadBuyerUX () { // get the html page to load let toLoad = 'buyer.html'; - // get the port to use for web socket communications with the server - getPort(); // if (buyers.length === 0) then autoLoad() was not successfully run before this web app starts, so the sie of the buyer list is zero // assume user has run autoLoad and rebuild member list // if autoLoad not yet run, then member list length will still be zero if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupBuyer(page[0], port[0]);}); - } - else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupBuyer(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupBuyer(page);}); + } + else{ + $.when($.get(toLoad)).done(function (page) + {setupBuyer(page);}); + } } -} - -function setupBuyer(page, port) -{ + + function setupBuyer(page) + { // empty the hetml element that will hold this page $('#buyerbody').empty(); $('#buyerbody').append(page); - // update the text on the page using the prompt data for the selected language + // empty the buyer alerts array + b_alerts = []; + // if there are no alerts, then remove the 'on' class and add the 'off' class + if (b_alerts.length === 0) + {$(b_notify).removeClass('on'); $(b_notify).addClass('off'); } + else {$(b_notify).removeClass('off'); $(b_notify).addClass('on'); } + // update the text on the page using the prompt data for the selected language updatePage('buyer'); - msgPort = port.port; - // connect to the web socket and tell the web socket where to display messages - wsDisplay('buyer_messages', msgPort); // enable the buttons to process an onClick event let _create = $('#newOrder'); let _list = $('#orderStatus'); @@ -67,8 +72,21 @@ function setupBuyer(page, port) } // display the name of the current buyer $('#company')[0].innerText = buyers[0].companyName; - // create a function to execute when the user selects a different buyer - $('#buyer').on('change', function() { _orderDiv.empty(); $('#buyer_messages').empty(); $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; }); + // save the current buyer id as b_id + b_id = buyers[0].id; + // subscribe to events + z2bSubscribe('Buyer', b_id); + // create a function to execute when the user selects a different buyer + $('#buyer').on('change', function() + { _orderDiv.empty(); $('#buyer_messages').empty(); + $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; + // unsubscribe the current buyer + z2bUnSubscribe(b_id); + // get the new buyer id + b_id = findMember($('#buyer').find(':selected').text(),buyers).id; + // subscribe the new buyer + z2bSubscribe('Buyer', b_id); + }); } /** @@ -97,7 +115,7 @@ function displayOrderForm() $('#amount').append('$'+totalAmount+'.00'); // build a select list for the items let _str = ''; - for (let each in itemTable){(function(_idx, _arr){_str+=''})(each, itemTable)} + for (let each in itemTable){(function(_idx, _arr){_str+='';})(each, itemTable);} $('#items').empty(); $('#items').append(_str); $('#cancelNewOrder').on('click', function (){_orderDiv.empty();}); @@ -185,8 +203,8 @@ function listOrders() * used by the listOrders() function * formats the orders for a buyer. Orders to be formatted are provided in the _orders array * output replaces the current contents of the html element identified by _target - * @param _target - string with div id prefaced by # - * @param _orders - array with order objects + * @param {String} _target - string with div id prefaced by # + * @param {Array} _orders - array with order objects */ function formatOrders(_target, _orders) { @@ -267,7 +285,7 @@ function formatOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    "+_curObj+""+_arr[_idx][_curObj]+"
    "+_curObj[0]+""+_curObj2+""+_arr2[_idx2][_curObj2[0]]+"
    '+_curObj+''+_arr[_idx][_curObj]+'
    '+_curObj[0]+''+_curObj2+''+_arr2[_idx2][_curObj2[0]]+'
    '; - _str += ''+_action+r_string+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.seller+findMember(_arr[_idx].seller.split('#')[1],sellers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+r_string+_button+''; _str+= '' for (let every in _arr[_idx].items) { @@ -286,18 +304,26 @@ function formatOrders(_target, _orders) // iterate through the page and make all of the different parts of the page active. // for (let each in _orders) - {(function(_idx, _arr) - { $('#b_btn_'+_idx).on('click', function () - { - let options = {}; - options.action = $('#b_action'+_idx).find(':selected').text(); - options.orderNo = $('#b_order'+_idx).text(); - options.participant = $('#buyer').val(); - if ((options.action === 'Dispute') || (options.action === 'Resolve')) {options.reason = $('#b_reason'+_idx).val();} - $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); - $.when($.post('/composer/client/orderAction', options)).done(function (_results) - { $('#buyer_messages').prepend(formatMessage(_results.result)); }); - }); - })(each, _orders) + {(function(_idx, _arr) + { $('#b_btn_'+_idx).on('click', function () + { + let options = {}; + options.action = $('#b_action'+_idx).find(':selected').text(); + options.orderNo = $('#b_order'+_idx).text(); + options.participant = $('#buyer').val(); + if ((options.action === 'Dispute') || (options.action === 'Resolve')) + {options.reason = $('#b_reason'+_idx).val();} + $('#buyer_messages').prepend(formatMessage(options.action+textPrompts.orderProcess.processing_msg.format(options.action, options.orderNo)+options.orderNo)); + $.when($.post('/composer/client/orderAction', options)).done(function (_results) + { $('#buyer_messages').prepend(formatMessage(_results.result)); }); + }); + // use the notifyMe function to determine if this order is in the alert array. + // if it is, the highlight the $('#b_status'+_idx) html element by adding the 'highlight' class + if (notifyMe(b_alerts, _arr[_idx].id)) {$('#b_status'+_idx).addClass('highlight'); } + })(each, _orders); } + // reset the b_alerts array to a new array + b_alerts = new Array(); + // call the toggleAlerts function to reset the alert icon + toggleAlert($('#buyer_notify'), b_alerts, b_alerts.length); } \ No newline at end of file diff --git a/Chapter11/HTML/js/z2b-events.js b/Chapter11/HTML/js/z2b-events.js index 74cf7d3..282f3ea 100644 --- a/Chapter11/HTML/js/z2b-events.js +++ b/Chapter11/HTML/js/z2b-events.js @@ -16,6 +16,8 @@ 'use strict'; +let wsSocket; + /** * load the four initial user roles into a single page. */ @@ -23,24 +25,30 @@ function singleUX () { let toLoad = 'singleUX.html'; if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (_page, _port, _res) - { - // get the msgPort - - // empty and reload the body div - - // call the load<> functions - + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); }); } else{ $.when($.get(toLoad)).done(function(_page) { - // empty and reload the body div - - // call the load<> functions - - }); + $('#body').empty(); + $('#body').append(_page); + loadBuyerUX(); + loadSellerUX(); + loadProviderUX(); + loadShipperUX(); + // Initialize Registration for all Z2B Business Events + goEventInitialize(); + }); } } /** @@ -60,15 +68,26 @@ function memberLoad () $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) { - buyers = _buyers[0].members; - sellers = _sellers[0].members; - s_string = _getMembers(sellers); - providers = _providers[0].members; - p_string = _getMembers(providers); - shippers = _shippers[0].members; - sh_string = _getMembers(shippers); + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); + s_string = _getMembers(sellers); + p_string = _getMembers(providers); + sh_string = _getMembers(shippers); + }); } +/** + * dropDummy() removes 'noop@dummy' from memberlist + * @param {String} _in - member id to ignore + */ +function dropDummy(_in) +{ + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} + return _a; +} /** * load all of the members in the network for use in the different user experiences. This routine is designed for use if the network has been newly deployed and the web app was * started before the autoLoad function was run on the newly deployed network (which, by default, is empty). @@ -87,27 +106,178 @@ function deferredMemberLoad() $.when($.post('/composer/admin/getMembers', options), $.post('/composer/admin/getMembers', options2), $.post('/composer/admin/getMembers', options3), $.post('/composer/admin/getMembers', options4)).done(function (_sellers, _buyers, _providers, _shippers) { - buyers = _buyers[0].members; - sellers = _sellers[0].members; + buyers = dropDummy(_buyers[0].members); + sellers = dropDummy(_sellers[0].members); + providers = dropDummy(_providers[0].members); + shippers = dropDummy(_shippers[0].members); s_string = _getMembers(sellers); - providers = _providers[0].members; p_string = _getMembers(providers); - shippers = _shippers[0].members; sh_string = _getMembers(shippers); d_prompts.resolve(); }).fail(d_prompts.reject); - return d_prompts.promise(); + return d_prompts.promise(); } /** * return an option list for use in an HTML '; return _str; +} +/** + * set up the server to listen for all events + */ +function goEventInitialize() +{ + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); +} + +/** + * @param {Event} _event - inbound Event + * @param {String} _id - subscriber target + * @param {String} _orderID - inbound order id + */ +function addNotification(_event, _id, _orderID) +{ + let method = 'addNotification'; + console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); + let type = getSubscriber(_id); + if (type === 'none') {return;} + switch(type) + { + case 'Buyer': + b_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(b_notify, b_alerts, b_count); + break; + case 'Seller': + s_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(s_notify, s_alerts, s_count); + break; + case 'Provider': + p_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(p_notify, p_alerts, p_count); + break; + case 'Shipper': + sh_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(sh_notify, sh_alerts, sh_count); + break; + case 'FinanceCo': + f_alerts.push({'event': _event, 'order': _orderID}); + toggleAlert(f_notify, f_alerts, f_count); + break; + default: + console.log(method+' default entered for: '+type); + break; + } +} +/** + * + * @param {jQuery} _target - jquery object to update + * @param {Array} _array - array of alerts for this member + * @param {jQuery} _count - jQuery object to hold alert count + */ +function toggleAlert(_target, _array, _count) +{ + if (_array.length < 1) + {$(_target).removeClass('on'); $(_target).addClass('off'); } + else {$(_count).empty(); $(_count).append(_array.length); + $(_target).removeClass('off'); $(_target).addClass('on'); } + +} +/** + * check to see if _id is subscribing + * @param {Integer} _id - member id to seek + * @returns {String} - type of member + */ +function getSubscriber(_id) +{ + let type = 'none'; + for (let each in subscribers){(function(_idx, _arr){if (_arr[_idx].id === _id){type=_arr[_idx].type;}})(each, subscribers);} + return(type); +} +/** + * subscribe to events + * @param {String} _type - member type + * @param {String} _id - member id + */ +function z2bSubscribe(_type, _id) +{ + subscribers.push({'type': _type, 'id': _id}); +} +/** + * Unsubscribe to events + * @param {String} _id - member id to remove + */ +function z2bUnSubscribe(_id) +{ + let _s1 = subscribers; + let _s2 = []; + for (let each in _s1) {(function(_idx, _arr){if (_arr[_idx] != _id){_s2.push(_arr[_idx]);}})(each, _s1);} + subscribers = _s2; +} +/** + * notifyMe + * @param {Array} _alerts - array of alerts + * @param {String} _id - orderID + * @returns {Boolean} - true if found, false if not found + */ +function notifyMe (_alerts, _id) +{ + let b_h = false; + for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} + return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter11/HTML/js/z2b-financeCo.js b/Chapter11/HTML/js/z2b-financeCo.js index a74a755..40ff08e 100644 --- a/Chapter11/HTML/js/z2b-financeCo.js +++ b/Chapter11/HTML/js/z2b-financeCo.js @@ -19,6 +19,11 @@ let financeCOorderDiv = 'financeCOorderDiv'; let orders = []; const financeCoID = 'easymoney@easymoneyinc.com'; +const financeCoName = 'The Global Financier'; +let f_notify = '#financeCo_notify'; +let f_id = 'easymoney@easymoneyinc.com'; +let f_count = '#financeCo_count'; +let f_alerts; /** * load the finance company User Experience @@ -26,33 +31,34 @@ const financeCoID = 'easymoney@easymoneyinc.com'; function loadFinanceCoUX () { let toLoad = 'financeCo.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupFinanceCo(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupFinanceCo(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupFinanceCo(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupFinanceCo(page);}); } } /** * @param {String} page HTML page to load - * @param {Integer} port Websocket port to use */ -function setupFinanceCo(page, port) +function setupFinanceCo(page) { $('#body').empty(); $('#body').append(page); + f_alerts = []; + if (f_alerts.length === 0) + {$(f_notify).removeClass('on'); $(f_notify).addClass('off'); } + else + {$(f_notify).removeClass('off'); $(f_notify).addClass('on'); } updatePage( 'financeCo'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('finance_messages', msgPort); let _clear = $('#financeCOclear'); let _list = $('#financeCOorderStatus'); let _orderDiv = $('#'+financeCOorderDiv); _clear.on('click', function(){_orderDiv.empty();}); _list.on('click', function(){listFinanceOrders();}); + z2bSubscribe('FinanceCo', f_id); } /** * lists all orders for the selected financier @@ -75,13 +81,13 @@ function listFinanceOrders() * used by the listOrders() function * formats the orders for a financier. Orders to be formatted are provided in the _orders array * output replaces the current contents of the html element identified by _target - * @param _target - string with div id prefaced by # - * @param _orders - array with order objects + * @param {String} _target - string with div id prefaced by # + * @param {Integer} _orders - array with order objects */ function formatFinanceOrders(_target, _orders) { _target.empty(); - let _str = ''; let _date = ''; + let _str = ''; let _date = ''; for (let each in _orders) {(function(_idx, _arr) { let _action = '
    '+_action+''+_button+'
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    '; - _str += ''+_action+''+_button+'
    Order #StatusTotalBuyer: '+findMember(_buyer,buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += '
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; _str+= formatDetail(_idx, _arr[_idx]); })(each, _orders); } @@ -171,11 +177,17 @@ function formatFinanceOrders(_target, _orders) $('#finance_messages').prepend(formatMessage(_results.result)); }); }); + if (notifyMe(f_alerts, _arr[_idx].id)) {$("#f_status"+_idx).addClass('highlight'); } })(each, _orders); } + f_alerts = new Array(); + toggleAlert($('#financeCo_notify'), f_alerts, f_alerts.length); } /** * format the accordian with the details for this order + * @param {Integer} _cur - offset into order array + * @param {JSON} _order - JSON object with current order data + * @returns {String} - html string to append to browser page */ function formatDetail(_cur, _order) { diff --git a/Chapter11/HTML/js/z2b-initiate.js b/Chapter11/HTML/js/z2b-initiate.js index bc5076a..7ba4493 100644 --- a/Chapter11/HTML/js/z2b-initiate.js +++ b/Chapter11/HTML/js/z2b-initiate.js @@ -20,7 +20,13 @@ let connectionProfileName = 'z2b-test-profile'; let networkFile = 'zerotoblockchain-network.bna'; let businessNetwork = 'zerotoblockchain-network'; -let buyers, sellers, providers, shippers; +let host_address = window.location.host; + +let buyers = new Array(); +let sellers= new Array(); +let providers= new Array(); +let shippers= new Array(); + let s_string, p_string, sh_string; let orderStatus = { @@ -53,4 +59,6 @@ function initPage () memberLoad(); // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring getChainEvents(); + // get the asynch port + wsConnect(); } diff --git a/Chapter11/HTML/js/z2b-provider.js b/Chapter11/HTML/js/z2b-provider.js index 68a670c..cc8d752 100644 --- a/Chapter11/HTML/js/z2b-provider.js +++ b/Chapter11/HTML/js/z2b-provider.js @@ -17,6 +17,10 @@ 'use strict'; let providerOrderDiv = 'providerOrderDiv'; +let p_alerts = []; +let p_notify = '#provider_notify'; +let p_count = '#provider_count'; +let p_id; /** * load the Provider User Experience @@ -24,30 +28,28 @@ let providerOrderDiv = 'providerOrderDiv'; function loadProviderUX () { let toLoad = 'provider.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupProvider(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupProvider(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupProvider(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupProvider(page);}); } } /** * load the Provider User Experience * @param {String} page - the name of the page to load - * @param {Integer} port - the port number to use */ -function setupProvider(page, port) +function setupProvider(page) { $('#providerbody').empty(); $('#providerbody').append(page); + if (p_alerts.length === 0) + {$(p_notify).removeClass('on'); $(p_notify).addClass('off'); } + else {$(p_notify).removeClass('off'); $(p_notify).addClass('on'); } updatePage('provider'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('provider_messages', msgPort); let _clear = $('#provider_clear'); let _list = $('#providerOrderStatus'); let _orderDiv = $('#'+providerOrderDiv); @@ -57,9 +59,15 @@ function setupProvider(page, port) $('#provider').append(p_string); $('#providerCompany').empty(); $('#providerCompany').append(providers[0].companyName); + p_id = providers[0].id; + z2bSubscribe('Provider', p_id); + // create a function to execute when the user selects a different provider $('#provider').on('change', function() { $('#providerCompany').empty(); _orderDiv.empty(); $('#provider_messages').empty(); $('#providerCompany').append(findMember($('#provider').find(':selected').val(),providers).companyName); + z2bUnSubscribe(p_id); + p_id = findMember($('#provider').find(':selected').text(),providers).id; + z2bSubscribe('Provider', p_id); }); } /** @@ -137,9 +145,6 @@ function formatProviderOrders(_target, _orders) _action += ''; b_string += '
    '+textPrompts.orderProcess.Refund.prompt+''; break; - case orderStatus.Cancelled.code: - _date = _arr[_idx].cancelled; - break; case orderStatus.Paid.code: _date = _arr[_idx].paid; break; @@ -150,7 +155,7 @@ function formatProviderOrders(_target, _orders) _action += ''; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+''+textPrompts.orderProcess.buyer+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+'
    '; @@ -143,7 +151,7 @@ function formatShipperOrders(_target, _orders) console.log('shipper _action: '+_action); if (_idx > 0) {_str += '
    ';} _str += ''; - _str += ''+_action+_statusText+''+_button+'
    '+textPrompts.orderProcess.orderno+''+textPrompts.orderProcess.status+''+textPrompts.orderProcess.total+'Buyer: '+findMember(_arr[_idx].buyer.split('#')[1],buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; + _str += ''+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00'+_action+_statusText+''+_button+''; _str+= '' for (let every in _arr[_idx].items) {(function(_idx2, _arr2) @@ -173,6 +181,9 @@ function formatShipperOrders(_target, _orders) $('#shipper_messages').prepend(formatMessage(_results.result)); }); }); + if (notifyMe(sh_alerts, _arr[_idx].id)) {$("#sh_status"+_idx).addClass('highlight'); } })(each, _orders); } -} \ No newline at end of file + sh_alerts = new Array(); + toggleAlert($('#shipper_notify'), sh_alerts, sh_alerts.length); + } \ No newline at end of file diff --git a/Chapter11/HTML/js/z2b-utilities.js b/Chapter11/HTML/js/z2b-utilities.js index ae1637f..7f2c962 100644 --- a/Chapter11/HTML/js/z2b-utilities.js +++ b/Chapter11/HTML/js/z2b-utilities.js @@ -6,68 +6,72 @@ * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, + * distributed under the License is distributed on an "AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -// z2c-utilities.js - +// z2c-utilities.js +'use strict'; /** * creates a set of utilities inside the named space: z2c * All utilities are accessed as z2c.functionName() * @namespace - z2c */ -languages = {}, // getSupportedLanguages -selectedLanguage = {}, -language = "", -textLocations = {}, // getTextLocations -textPrompts = {}, // getSelectedPromots +let languages = {}, // getSupportedLanguages + selectedLanguage = {}, + language = '', + textLocations = {}, // getTextLocations + textPrompts = {}, // getSelectedPromots + subscribers = new Array(); // subscribers to business events /** * get the value associated with a cookie named in the input * Refer to this by {@link getCookieValue}. * @param {String} _name - the name of the cookie to find -* @namespace +* @returns {String} - cookie value +* @namespace */ function getCookieValue(_name) { - var name = _name+"="; - var cookie_array= document.cookie.split(";"); - for (each in cookie_array) - { var c = cookie_array[each].trim(); - if(c.indexOf(name) == 0) return(c.substring(name.length, c.length)); - } - return(""); + let name = _name+'='; + let cookie_array= document.cookie.split(';'); + for (let each in cookie_array) + { + let c = cookie_array[each].trim(); + if(c.indexOf(name) === 0) {return(c.substring(name.length, c.length));} + } + return(''); } /** * trims a string by removing all leading and trailing spaces * trims the final period, if it exists, from a string. * Refer to this by {@link trimStrip}. -* @param {String} _string String to be trimmed and stripped of trailing period -* @namespace +* @param {String} _string - String to be trimmed and stripped of trailing period +* @returns {String} - trimmed string +* @namespace */ function trimStrip(_string) { - var str = _string.trim(); - var len = str.length; - if(str.endsWith(".")) {str=str.substring(0,len-1);} - return(str); + let str = _string.trim(); + let len = str.length; + if(str.endsWith('.')) {str=str.substring(0,len-1);} + return(str); } /** * replaces text on an html page based on the anchors and text provided in a JSON textPrompts object * Refer to this by {@link updatePage}. * @param {String} _page - a string representing the name of the html page to be updated -* @namespace +* @namespace */ function updatePage(_page) { - for (each in textPrompts[_page]){(function(_idx, _array) - {$("#"+_idx).empty();$("#"+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} + for (let each in textPrompts[_page]){(function(_idx, _array) + {$('#'+_idx).empty();$('#'+_idx).append(getDisplaytext(_page, _idx));})(each, textPrompts[_page])} } /** @@ -75,7 +79,8 @@ function updatePage(_page) * Refer to this by {@link getDisplaytext}. * @param {String} _page - string representing the name of the html page to be updated * @param {String} _item - string representing the html named item to be updated -* @namespace +* @returns {String} - text to be placed on web page +* @namespace */ function getDisplaytext(_page, _item) {return (textPrompts[_page][_item]);} @@ -85,54 +90,56 @@ function getDisplaytext(_page, _item) * Refer to this by {@link goMultiLingual}. * @param {String} _language - language to be used in this session * @param {String} _page - string representing html page to be updated in the selected language -* @namespace +* @namespace */ function goMultiLingual(_language, _page) { language = _language; - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - {languages = _res; - selectedLanguage = languages[_language]; - var options = {}; options.language = _language; - $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) - {textLocations = _locations; - textPrompts = JSON.parse(_prompts[0]); - updatePage(_page); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + {languages = _res; + selectedLanguage = languages[_language]; + let options = {}; options.language = _language; + $.when($.get('/api/getTextLocations'),$.post('/api/selectedPrompts', options)).done(function(_locations, _prompts) + {textLocations = _locations; + textPrompts = JSON.parse(_prompts[0]); + updatePage(_page); + }); + let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • '} + })(each, _res); + } + _choices.append(_str); }); - var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); } /** * get SupportedLanguages returns an html menu object with available languages * Refer to this by {@link getSupportedLanguages}. -* @namespace +* @namespace */ function getSupportedLanguages() { - $.when($.get("/api/getSupportedLanguages")).done(function(_res) - { - languages = _res; console.log(_res); var _choices = $("#lang_choices"); - _choices.empty(); var _str = ""; - for (each in _res) - {(function(_idx, _array) - {if (_array[_idx].active == "yes") - {_str += '
  • '+_array[_idx].menu+'
  • '} - })(each, _res)} - _choices.append(_str); - }); + $.when($.get('/api/getSupportedLanguages')).done(function(_res) + { + languages = _res; console.log(_res); let _choices = $('#lang_choices'); + _choices.empty(); let _str = ''; + for (let each in _res) + {(function(_idx, _array) + {if (_array[_idx].active === 'yes') + {_str += '
  • '+_array[_idx].menu+'
  • ';} + })(each, _res); + } + _choices.append(_str); + }); } /** * returns a JSON object with the pages and objects which support text replacement * Refer to this by {@link getTextLocations}. -* @namespace +* @namespace */ function getTextLocationsfunction () {$.when($.get('/api/getTextLocations')).done(function(_res){textLocations = _res; console.log(_res); });} @@ -140,38 +147,39 @@ function getTextLocationsfunction () /** * returns a JSON object with the text to be used to update identified pages and objects * Refer to this by {@link getSelectedPrompts}. -* @param {String} _inbound -* @namespace +* @param {String} _inbound - page or object to receive updated text +* @namespace */ function getSelectedPrompts(_inbound) { selectedLanguage=languages[_inbound]; - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function(_res){textPrompts = _res; console.log(_res); }); } /** * retrieves the prompts for the requested language from the server * Refer to this by {@link qOnSelectedPrompts}. * @param {String} _inbound - string representing the requested language -* @namespace +* @returns {Promise} - returns promise when selected prompts have been retrieved from server +* @namespace */ function qOnSelectedPrompts(_inbound) { - var d_prompts = $.Deferred(); - var options = {}; options.language = _inbound; - $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); - return d_prompts.promise(); + let d_prompts = $.Deferred(); + let options = {}; options.language = _inbound; + $.when($.post('/api/selectedPrompts', options)).done(function (p) {d_prompts.resolve(p);}).fail(d_prompts.reject); + return d_prompts.promise(); } /** * function to display the properties of an object using console.log * Refer to this by {@link displayObjectProperties}. * @param {Object} _obj - the object whose properties are to be displayed -* @namespace +* @namespace */ function displayObjectProperties(_obj) { - for(var propt in _obj){ console.log("object property: "+propt ); } + for(let propt in _obj){ console.log('object property: '+propt ); } } /** @@ -179,12 +187,12 @@ function displayObjectProperties(_obj) * Refer to this by {@link displayObjectValues}. * @param {String} _string - an arbitrary string to preface the printing of the object property name and value. often used to display the name of the object being printed * @param {Object} _object - the object to be introspected -* @namespace +* @namespace */ function displayObjectValues(_string, _object) { - for (prop in _object){ - console.log(_string+prop+": "+(((typeof(_object[prop]) == 'object') || (typeof(_object[prop]) == 'function')) ? typeof(_object[prop]) : _object[prop])); + for (let prop in _object){ + console.log(_string+prop+': '+(((typeof(_object[prop]) === 'object') || (typeof(_object[prop]) === 'function')) ? typeof(_object[prop]) : _object[prop])); } } @@ -201,124 +209,126 @@ function displayObjectValues(_string, _object) */ String.prototype.format = function(i, safe, arg) { +/** + * the format function added to String.prototype + * @returns {String} - returns original string with {x} replaced by provided text + */ + function format() { + let str = this, len = arguments.length+1; - function format() { - var str = this, len = arguments.length+1; - - // For each {0} {1} {n...} replace with the argument in that position. If - // the argument is an object or an array it will be stringified to JSON. - for (i=0; i < len; arg = arguments[i++]) { - safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; - str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + // For each {0} {1} {n...} replace with the argument in that position. If + // the argument is an object or an array it will be stringified to JSON. + for (i=0; i < len; arg = arguments[i++]) { + safe = typeof arg === 'object' ? JSON.stringify(arg) : arg; + str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe); + } + return str; } - return str; - } - // Save a reference of what may already exist under the property native. - // Allows for doing something like: if("".format.native) { /* use native */ } - format.native = String.prototype.format; - - // Replace the prototype property - return format; + // Save a reference of what may already exist under the property native. + // Allows for doing something like: if(''.format.native) { /* use native */ } + format.native = String.prototype.format; + // Replace the prototype property + return format; }(); /** * display the hyperledger apis as currently understood * Refer to this by {@link showAPIDocs}. - * + * */ function showAPIDocs() { - $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) - { - var _target = $("#body"); - _target.empty(); _target.append(_page[0]); - displayAPI(_res[0]); - }); + $.when($.get('/resources/getDocs'),$.get('hfcAPI.html')).done(function(_res, _page) + { + let _target = $('#body'); + _target.empty(); _target.append(_page[0]); + displayAPI(_res[0]); + }); } /** - * - * @param {JSON} _api + * + * @param {JSON} _api * Refer to this by {@link displayAPI}. - * + * */ function displayAPI(_api) { - var _exports = _api.hfcExports; - var _classes = _api.hfcClasses; - var _eTarget = $("#hfc_exports"); - var _cTarget = $("#hfc_classes"); - var _str = ""; - for (each in _exports) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - _str += ""; - })(each, _exports); - } - _eTarget.append(_str); - _str = ""; - for (each in _classes) { - (function(_idx, _arr){ - _curObj = Object.getOwnPropertyNames(_arr[_idx]); - for (every in _arr[_idx][_curObj[0]]){ - (function(_idx2, _arr2) - { - _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); - _str+= ""; - })(every, _arr[_idx][_curObj[0]]) - } - })(each, _classes); - } - _cTarget.append(_str); + let _exports = _api.hfcExports; + let _classes = _api.hfcClasses; + let _eTarget = $('#hfc_exports'); + let _cTarget = $('#hfc_classes'); + let _str = ''; + for (let each in _exports) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + _str += ''; + })(each, _exports); + } + _eTarget.append(_str); + _str = ''; + for (let each in _classes) { + (function(_idx, _arr){ + let _curObj = Object.getOwnPropertyNames(_arr[_idx]); + for (let every in _arr[_idx][_curObj[0]]){ + (function(_idx2, _arr2) + { + let _curObj2 = Object.getOwnPropertyNames(_arr2[_idx2]); + _str+= ''; + })(every, _arr[_idx][_curObj[0]]); + } + })(each, _classes); + } + _cTarget.append(_str); } /** * format messages for display + * @param {String} _msg - text to be enclosed in html message format + * @returns {String} - html formatted message */ function formatMessage(_msg) {return '

    '+_msg+'

    ';} + /** - * get the web socket port + * closes all accordians in this div + * @param {String} target - formatted jQuery string pointing to div with all accordians to collapse */ -function getPort () +function accOff(target) { - if (msgPort == null) - { $.when($.get('/setup/getPort')).done(function (port){console.log('port is: '+port.port); msgPort = port.port;});} + let thisElement = $(target); + let childNodes = thisElement.children(); + for (let each in childNodes) + {let node = '#'+childNodes[each].id; + if (node !== '#') + { + if($(node).hasClass('on')) {$(node).removeClass('on');} + $(node).addClass('off'); + } + } } + /** * toggle an accordian window + * @param {String} _parent - Div holding all accordians + * @param {String} _body - Div which only appears when accordian is expanded + * @param {HTMLDiv} _header - Div which appears when accordian is collapsed */ function accToggle(_parent, _body, _header) { - var parent = "#"+_parent; - var body="#"+_body; - var header = _header; - if ($(body).hasClass("on")) - {$(body).removeClass("on"); $(body).addClass("off"); - $(parent).removeClass("on"); $(parent).addClass("off"); - }else - { - accOff(parent); - $(body).removeClass("off"); $(body).addClass("on"); - $(parent).removeClass("off"); $(parent).addClass("on"); - } -} -/** - * - */ -function accOff(target) -{ - var thisElement = $(target); - var childNodes = thisElement.children(); - for (each in childNodes) - {var node = "#"+childNodes[each].id; - if (node != '#') - { - if($(node).hasClass("on")) {$(node).removeClass("on");} - $(node).addClass("off"); - } - } + let parent = '#'+_parent; + let body='#'+_body; + if ($(body).hasClass('on')) + { + $(body).removeClass('on'); $(body).addClass('off'); + $(parent).removeClass('on'); $(parent).addClass('off'); + }else + { + accOff(parent); + $(body).removeClass('off'); $(body).addClass('on'); + $(parent).removeClass('off'); $(parent).addClass('on'); + } } diff --git a/Chapter11/controller/restapi/features/composer/Z2B_Services.js b/Chapter11/controller/restapi/features/composer/Z2B_Services.js index 21dbb85..c4f8aa4 100644 --- a/Chapter11/controller/restapi/features/composer/Z2B_Services.js +++ b/Chapter11/controller/restapi/features/composer/Z2B_Services.js @@ -13,16 +13,18 @@ */ 'use strict'; -var fs = require('fs'); -var path = require('path'); +let fs = require('fs'); +let path = require('path'); const sleep = require('sleep'); -const ws = require('websocket'); -const http = require('http'); +// const ws = require('websocket'); +// const http = require('http'); +// const url = require('url'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); const appEnv = cfenv.getAppEnv(); +const util = require('./Z2B_Utilities'); app.set('port', appEnv.port); @@ -37,7 +39,7 @@ app.set('port', appEnv.port); * @class * @memberof module:Z2Blockchain */ -var Z2Blockchain = { +let Z2Blockchain = { /** * create an empty order. This is used by any server side routine that needs to create an new @@ -105,8 +107,8 @@ var Z2Blockchain = { /** * update item quantity. used by the autoLoad process. * @param {item_number} _itemNo - item number to find - * @param {vendor_array} _itemArray - item array from order * @param {item_number} _qty - quantity to change * @utility + * @param {vendor_array} _itemArray - item array from order */ setItem: function (_itemNo, _qty, _itemArray) { @@ -115,46 +117,78 @@ var Z2Blockchain = { }, /** * supplemental routine to resubmit orders when MVCC_READ_CONFLICT encountered + * @param {object} _con - web socket connection * @param {transaction} _item - transaction to process * @param {order_object} _id - order id - * @param {bnc} businessNetworkConnection - already created business network connection + * @param {BusinessNetworkConnection} businessNetworkConnection - already created business network connection + * @returns {promise} promise */ loadTransaction: function (_con, _item, _id, businessNetworkConnection) { + let method = 'loadTransaction'; return businessNetworkConnection.submitTransaction(_item) .then(() => { - console.log('loadTransaction: order '+_id+' successfully added'); - _con.sendUTF('loadTransaction: order '+_id+' successfully added'); + console.log(method+': order '+_id+' successfully added '); + this.send(_con, 'Message', 'Order '+_id+' successfully added'); }) .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) + if (error.message.search('MVCC_READ_CONFLICT') !== -1) {sleep.sleep(5); - console.log(_id+" loadTransaction retrying submit transaction for: "+_id); - this.loadTransaction(_con,_item, _id, businessNetworkConnection); + console.log(_id+' loadTransaction retrying submit transaction for: '+_id); + this.loadTransaction(_con, _item, _id, businessNetworkConnection); } }); }, /** * add an order to a registry. This adds an Asset and does not execute a transaction - * @param {order_object} _order - order_object to process - * @param {assetRegistry} _registry - registry into which asset (order) should be placed + * @param {order_object} _con - websocket + * @param {assetRegistry} _order - order_object to process + * @param {networkTransaction} _registry - registry into which asset (order) should be placed * @param {networkTransaction} _createNew - transaction to be processed after order successfully added - * @param {businessNetworkConnection} _bnc - business network connection to use */ - addOrder: function (_con, _order, _registry, _createNew, _bnc) - { - return _registry.add(_order) - .then(() => { - this.loadTransaction(_con,_createNew, _order.orderNumber, _bnc); - }) - .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) - {console.log(_order.orderNumber+" addOrder retrying assetRegistry.add for: "+_order.orderNumber); - this.addOrder(_con,_order, _registry, _createNew, _bnc); - } - else {console.log('error with assetRegistry.add', error)} - }); + * @param {businessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +addOrder: function (_con, _order, _registry, _createNew, _bnc) +{ + let method = 'addOrder'; + return _registry.add(_order) + .then(() => { + this.loadTransaction(_con, _createNew, _order.orderNumber, _bnc); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(_order.orderNumber+' addOrder retrying assetRegistry.add for: '+_order.orderNumber); + this.addOrder(_con, _order, _registry, _createNew, _bnc); + } + else {console.log(method+' error with assetRegistry.add', error);} + }); }, +/** + * repeats the bind identity request + * @param {WebSocket} _con - order_object to process + * @param {String} _id - registry into which asset (order) should be placed + * @param {String} _cert - transaction to be processed after order successfully added + * @param {BusinessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +bindIdentity: function (_con, _id, _cert, _bnc) +{ + let method = 'bindIdentity'; + console.log(method+' retrying bindIdentity for: '+_id); + return _bnc.bindIdentity(_id, _cert) + .then(() => { + console.log(method+' Succeeded for: '+_id); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(' bindIdentity retrying _bnc.bindIdentity(_id, _cert) for: '+_id); + this.bindIdentity(_con, _id, _cert, _bnc); + } + else {console.log(method+' error with _bnc.bindIdentity(_id, _cert) for: '+_id+' with error: ', error);} + }); +}, + /** * saves the member table with ids and secrets * @param {array} _table - array of JSON objects to save to file @@ -166,23 +200,26 @@ var Z2Blockchain = { let _mem = '{"members": ['; for (let each in _table) {(function(_idx, _arr) - {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table)} + {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table);} _mem += ']}'; fs.writeFileSync(newFile, _mem, options); }, /** * saves the item table * @param {array} _table - array of JSON objects to save to file + * @param {JSON} _table - data to be saved */ - saveItemTable: function (_table) - { - let options = { flag : 'w' }; - let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); - let _mem = '{"items": ['; - for (let each in _table) - {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table)} - _mem += ']}'; - fs.writeFileSync(newFile, _mem, options); - }, +saveItemTable: function (_table) +{ + console.log('_table: ', _table); + let options = { flag : 'w' }; + let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); + let _mem = '{"items": ['; + for (let each in _table) + {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table);} + _mem += ']}'; + console.log('_mem: ', _mem); + fs.writeFileSync(newFile, _mem, options); +}, /** * update an empty order with 4 items. update the amount field based on the sum of the line items * @param {addItems} _inbound - Order created with factory.newResource(NS, 'Order',.orderNumber) @@ -205,7 +242,7 @@ var Z2Blockchain = { _arr[_idx].extendedPrice = _item.unitPrice*_arr[_idx].quantity; _amount += _arr[_idx].extendedPrice; _items.push(JSON.stringify(_arr[_idx])); - })(each, _inbound.items)} + })(each, _inbound.items);} return ({'items': _items, 'amount': _amount}); }, /** @@ -213,22 +250,23 @@ var Z2Blockchain = { * was not initially working. This function is no longer in use. * @param {Order} _order - the inbound Order item retrieved from a registry * @return JSON object order elements + * @return {Order} JSON object order elements * @function */ - getOrderData: function (_order) - { - let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', - 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; - var _obj = {}; - for (let each in orderElements){(function(_idx, _arr) - { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements)} - _obj.buyer = _order.buyer.$identifier; - _obj.seller = _order.seller.$identifier; - _obj.provider = _order.seller.$provider; - _obj.shipper = _order.seller.$shipper; - _obj.financeCo = _order.seller.$financeCo; - return (_obj); - }, +getOrderData: function (_order) +{ + let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', + 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; + let _obj = {}; + for (let each in orderElements){(function(_idx, _arr) + { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements);} + _obj.buyer = _order.buyer.$identifier; + _obj.seller = _order.seller.$identifier; + _obj.provider = _order.seller.$provider; + _obj.shipper = _order.seller.$shipper; + _obj.financeCo = _order.seller.$financeCo; + return (_obj); +}, /** * JSON object of available order status types and codes. This is used by nodejs @@ -252,67 +290,15 @@ var Z2Blockchain = { Refunded: {code: 13, text: 'Order Refunded'} }, /** - * the user experience is enhanced if the browser can be notified of aysnchronous events. - * the createMessateSockt function creates a web socket service to which the browser can - * attach. - * @param {integer} _port - port number to use for this socket connection - * @returns {websocket} - web socket connection to be used on the server side. - */ - m_connection: null, - m_socketAddr: null, - m_socket: null, - createMessageSocket: function (_port) - { - var port = (typeof(_port) == 'undefined' || _port == null) ? app.get('port')+1 : _port - if (this.m_socket == null) - { - this.m_socketAddr = port; - this.m_socket= new ws.server({httpServer: http.createServer().listen(this.m_socketAddr)}); - var _this = this; - this.m_socket.on('request', function(request) - { - _this.m_connection = request.accept(null, request.origin); - _this.m_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.m_connection.sendUTF('connected'); - _this.m_connection.on('close', function(m_connection) {console.log('m_connection closed'); }); - }); - }); - } - return {conn: this.m_connection, socket: this.m_socketAddr}; - }, -/** - * the cs_connection is used to display blockchain information to the web browser over - * a sepaarate port from the user experience socket. - * @returns {websocket} - web socket connection to be used on the server side. + * New code to support sending messages to socket clients + * @param {Object} _locals - shared variables and functions from index.js + * @param {String} type - type of event message to put on channel + * @param {Event} event - event message */ - - cs_connection: null, - cs_socketAddr: null, - cs_socket: null, - createChainSocket: function () - { - var port = app.get('port')+2; - if (this.cs_socket == null) - { - this.cs_socketAddr = port; - this.cs_socket= new ws.server({httpServer: http.createServer().listen(this.cs_socketAddr)}); - var _this = this; - this.cs_socket.on('request', function(request) - { - _this.cs_connection = request.accept(null, request.origin); - _this.cs_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.cs_connection.sendUTF('connected'); - _this.cs_connection.on('close', function(cs_connection) {console.log('cs_connection closed'); }); - }); - }); - } - return {conn: this.cs_connection, socket: this.cs_socketAddr}; - } - +send: function (_locals, type, event) +{ + _locals.processMessages({'type': type, 'data': event} ); } +}; module.exports = Z2Blockchain; \ No newline at end of file diff --git a/Chapter11/controller/restapi/features/composer/autoLoad.js b/Chapter11/controller/restapi/features/composer/autoLoad.js index ce3d81b..da256aa 100644 --- a/Chapter11/controller/restapi/features/composer/autoLoad.js +++ b/Chapter11/controller/restapi/features/composer/autoLoad.js @@ -34,32 +34,13 @@ const financeCoID = 'easymoney@easymoneyinc.com'; const svc = require('./Z2B_Services'); const config = require('../../../env.json'); + /** * itemTable and memberTable are used by the server to reduce load time requests * for member secrets and item information */ let itemTable = new Array(); let memberTable = new Array(); -let socketAddr; - - - - - -/** - * getPort is used to return the port number for socket interactions so that - * the browser can receive asynchronous notifications of work in process. - * This helps the user understand the current status of the auto load process. - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * - * @function - */ -exports.getPort = function(req, res, next) { - let _conn = svc.createMessageSocket(); - res.send({'port': _conn.socket}); -}; /** * autoLoad reads the memberList.json file from the Startup folder and adds members, @@ -78,9 +59,9 @@ exports.autoLoad = function(req, res, next) { // connect to the network let businessNetworkConnection; let factory; let participant; - svc.createMessageSocket(); - socketAddr = svc.m_socketAddr; - let adminConnection = new AdminConnection(); +// svc.createMessageSocket(); +// socketAddr = svc.m_socketAddr; +let adminConnection = new AdminConnection(); // connection prior to V0.15 // adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW) // connection in v0.15 @@ -110,7 +91,7 @@ exports.autoLoad = function(req, res, next) { return participantRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { participant = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); @@ -118,7 +99,7 @@ exports.autoLoad = function(req, res, next) { participantRegistry.add(participant) .then(() => { console.log('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); - svc.m_connection.sendUTF('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); + svc.send(req.app.locals, 'Message', '['+_idx+'] '+_arr[_idx].companyName+' successfully added'); }) .then(() => { // an identity is required before a member can take action in the network. @@ -144,7 +125,9 @@ exports.autoLoad = function(req, res, next) { config.connectionProfile.keyValStore = _home+config.connectionProfile.keyValStore; let tempCard = new hlc_idCard(_meta, config.connectionProfile); return adminConnection.importCard(result.userID, tempCard) - .then ((_res) => { if (_res) {console.log('card updated');} else {console.log('card imported');} }) + .then ((_res) => { + if (_res) {console.log('card updated');} else {console.log('card imported');} + }) .catch((error) => { console.error('adminConnection.importCard failed. ',error.message); }); @@ -172,7 +155,7 @@ exports.autoLoad = function(req, res, next) { return assetRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { // first, an Order Object is created @@ -186,8 +169,8 @@ exports.autoLoad = function(req, res, next) { const createNew = factory.newTransaction(config.composer.NS, 'CreateOrder'); order.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); order.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); - order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummy'); - order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummy'); + order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummyProvider'); + order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummyShipper'); order.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.order = factory.newRelationship(config.composer.NS, 'Order', order.$identifier); @@ -199,7 +182,7 @@ exports.autoLoad = function(req, res, next) { .then(() => { // then a createOrder transaction is processed which uses the chaincode // establish the order with it's initial transaction state. - svc.loadTransaction(svc.m_connection, createNew, order.orderNumber, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, order.orderNumber, businessNetworkConnection); }) .catch((error) => { // in the development environment, because of how timing is set up, it is normal to @@ -207,8 +190,8 @@ exports.autoLoad = function(req, res, next) { // logical transaction error. if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log('AL: '+_arr[_idx].id+' retrying assetRegistry.add for: '+_arr[_idx].id); - svc.addOrder(svc.m_connection, order, assetRegistry, createNew, businessNetworkConnection); - } + svc.addOrder(req.app.locals, order, assetRegistry, createNew, businessNetworkConnection); + } else {console.log('error with assetRegistry.add', error.message);} }); }); @@ -220,7 +203,7 @@ exports.autoLoad = function(req, res, next) { .catch((error) => {console.log('error with business network Connect', error.message);}); }) .catch((error) => {console.log('error with adminConnect', error.message);}); - res.send({'port': socketAddr}); + res.send({'result': 'Success'}); }; /** diff --git a/Chapter11/controller/restapi/features/composer/hlcAdmin.js b/Chapter11/controller/restapi/features/composer/hlcAdmin.js index 8e9e8b9..46b188c 100644 --- a/Chapter11/controller/restapi/features/composer/hlcAdmin.js +++ b/Chapter11/controller/restapi/features/composer/hlcAdmin.js @@ -24,8 +24,7 @@ const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefi const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; -// const svc = require('./Z2B_Services'); -// const mod = 'hlcAdmin.js'; + /** * display the admin and network info diff --git a/Chapter11/controller/restapi/features/composer/hlcClient.js b/Chapter11/controller/restapi/features/composer/hlcClient.js index bc5bfb6..fc7955c 100644 --- a/Chapter11/controller/restapi/features/composer/hlcClient.js +++ b/Chapter11/controller/restapi/features/composer/hlcClient.js @@ -18,11 +18,12 @@ let fs = require('fs'); let path = require('path'); const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition; -// const config = require('../../../env.json'); +const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; let itemTable = null; const svc = require('./Z2B_Services'); const financeCoID = 'easymoney@easymoneyinc.com'; +let bRegistered = false; /** * get orders for buyer with ID = _id @@ -244,7 +245,7 @@ exports.orderAction = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(' retrying assetRegistry.update for: '+req.body.orderNo); - svc.loadTransaction(svc.m_connection, updateOrder, req.body.orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, updateOrder, req.body.orderNo, businessNetworkConnection); } else {console.log(req.body.orderNo+' submitTransaction to update status to '+req.body.action+' failed with text: ',error.message);} @@ -329,7 +330,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else {console.log(orderNo+' submitTransaction failed with text: ',error.message);} @@ -338,7 +339,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else { @@ -353,7 +354,97 @@ exports.addOrder = function (req, res, next) { }); }) .catch((error) => { - console.log(orderNo+' business network connection failed: text',error.message); + console.log(method + ' : '+orderNo+' business network connection failed: text',error.message); res.send({'result': 'failed', 'error':' order '+orderNo+' add failed on on business network connection '+error.message}); }); }; + +/** + * _monitor + * @param {WebSocket} _conn - web socket to use for member event posting + * @param {WebSocket} _f_conn - web sockect to use for FinanceCo event posting + * @param {Event} _event - the event just emitted + * + */ +function _monitor(locals, _event) +{ + let method = '_monitor'; + console.log(method+ ' _event received: '+_event.$type+' for Order: '+_event.orderID); + // create an event object and give it the event type, the orderID, the buyer id and the eventID + // send that event back to the requestor + // ========> Your Code Goes Here <========= + + // using switch/case logic, send events back to each participant who should be notified. + // for example, when a seller requests payment, they should be notified when the transaction has completed + // and the financeCo should be notified at the same time. + // so you would use the _conn connection to notify the seller and the + // _f_conn connection to notify the financeCo + + switch (_event.$type) + { + case 'Created': + break; + case 'Bought': + case 'PaymentRequested': + // ========> Your Code Goes Here <========= + break; + case 'Ordered': + case 'Cancelled': + case 'Backordered': + // ========> Your Code Goes Here <========= + break; + case 'ShipRequest': + case 'DeliveryStarted': + case 'DeliveryCompleted': + // ========> Your Code Goes Here <========= + break; + case 'DisputeOpened': + case 'Resolved': + case 'Refunded': + case 'Paid': + // ========> Your Code Goes Here <========= + break; + case 'PaymentAuthorized': + // ========> Your Code Goes Here <========= + break; + default: + break; + } + +} + +/** + * Register for all of the available Z2BEvents + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + * @returns {Object} - returns are via res.send +*/ +exports.init_z2bEvents = function (req, res, next) +{ + let method = 'init_z2bEvents'; + if (bRegistered) {res.send('Already Registered');} + else{ + bRegistered = true; +// svc.createAlertSocket(); + let businessNetworkConnection; + businessNetworkConnection = new BusinessNetworkConnection(); + businessNetworkConnection.setMaxListeners(50); + // + // v0.14 + // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // + // v0.15 + return businessNetworkConnection.connect(config.composer.adminCard) + .then(() => { + // using the businessNetworkConnection, start monitoring for events. + // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information + businessNetworkConnection.on('event', (event) => {_monitor(req.app.locals, event); }); + res.send('event registration complete'); + }).catch((error) => { + // if an error is encountered, log the error and send it back to the requestor + console.log(method+' business network connection failed'+error.message); + res.send(method+' business network connection failed'+error.message); + }); + } +}; diff --git a/Chapter11/controller/restapi/features/composer/queryBlockChain.js b/Chapter11/controller/restapi/features/composer/queryBlockChain.js index 9b6a396..75b67d3 100644 --- a/Chapter11/controller/restapi/features/composer/queryBlockChain.js +++ b/Chapter11/controller/restapi/features/composer/queryBlockChain.js @@ -12,8 +12,9 @@ * limitations under the License. */ -var path = require('path'); -var fs = require('fs'); +'use strict'; +let path = require('path'); +let fs = require('fs'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); @@ -24,10 +25,10 @@ const hfc = require('fabric-client'); const hfcEH = require('fabric-client/lib/EventHub'); const svc = require('./Z2B_Services'); -const util = require('./Z2B_Utilities'); -const financeCoID = 'easymoney@easymoneyinc.com'; +// const util = require('./Z2B_Utilities'); +// const financeCoID = 'easymoney@easymoneyinc.com'; const config = require('../../../env.json'); -var chainEvents = false; +let chainEvents = false; @@ -38,11 +39,13 @@ var chainEvents = false; * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainInfo = function(req, res, next) { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); - console.log(wallet_path); +exports.getChainInfo = function(req, res, next) +{ + let method='getChainInfo'; + let HOST_NAME = req.headers.host; + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); Promise.resolve().then(() => { // // As of 9/28/2017 there is a known and unresolved bug in HyperLedger Fabric @@ -61,29 +64,43 @@ exports.getChainInfo = function(req, res, next) { // change PeerAdmin in following line to adminID return client.getUserContext(config.composer.PeerAdmin, true);}) .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + if (user === null || user === undefined || user.isEnrolled() === false) + { console.error('User not defined, or not enrolled - error');} + if (HOST_NAME.slice(0,9) === 'localhost') + { + console.log(method+" running locally"); channel = client.newChannel(config.fabric.channelName); channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - }) + }else + { + console.log(method+" running remotely, not supported in Chapter 12"); + } + }) .then(() => { return channel.queryInfo() .then((blockchainInfo) => { if (blockchainInfo) { - res.send({"result": "success", "currentHash": blockchainInfo.currentBlockHash.toString("hex"), blockchain: blockchainInfo}); + res.send({'result': 'success', 'currentHash': blockchainInfo.currentBlockHash.toString('hex'), blockchain: blockchainInfo}); } else { console.log('response_payload is null'); - res.send({"result": "uncertain", "message": 'response_payload is null'}); + res.send({'result': 'uncertain', 'message': 'response_payload is null'}); } }) .catch((_err) => { - console.log("queryInfo failed with _err = ", _err); - res.send({"result": "failed", "message": _err.message}); - }); + console.log('queryInfo failed with _err = ', _err); + res.send({'result': 'failed', 'message': _err.message}); + }); }); - }); -} + }); +}; /** * get chain events @@ -92,37 +109,55 @@ exports.getChainInfo = function(req, res, next) { * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainEvents = function(req, res, next) { +exports.getChainEvents = function(req, res, next) +{ + let method = 'getChainEvents'; + let HOST_NAME = req.headers.host; if (chainEvents) {res.send({'port': svc.cs_socketAddr});} else { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); + Promise.resolve().then(() => { client = new hfc(); return hfc.newDefaultKeyValueStore({ path: wallet_path }) .then((wallet) => { client.setStateStore(wallet); // change PeerAdmin in following line to adminID - return client.getUserContext(config.composer.PeerAdmin, true);}) - .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} - channel = client.newChannel(config.fabric.channelName); - channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); - channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - // change Admin in following line to admin - var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); - var adminPEM = fs.readFileSync(pemPath).toString(); - var bcEvents = new hfcEH(client); - bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + return client.getUserContext(config.composer.PeerAdmin, true); + }) + .then((user) => { + if (user === null || user === undefined || user.isEnrolled() === false) + {console.error(method+': User not defined, or not enrolled - error');} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + // get the channel name + channel = client.newChannel(config.fabric.channelName); + //get the request URL for the Peer0 container + channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); + // get the orderer URL + channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); + // change Admin in following line to admin + var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); + var adminPEM = fs.readFileSync(pemPath).toString(); + var bcEvents = new hfcEH(client); + bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + bcEvents.registerBlockEvent( + function(event){svc.send(req.app.locals, 'BlockChain', event);}, + function(error){console.log(method+': registerBlockEvent error: ', error);} + ); bcEvents.connect(); - svc.createChainSocket(); - bcEvents.registerBlockEvent(function(event) {svc.cs_connection.sendUTF(JSON.stringify(event));}); - chainEvents = true; - res.send({'port': svc.cs_socketAddr}); - }) - }); - } -} + chainEvents = true; + res.send({'port': svc.cs_socketAddr}); + }) + .catch((err) => { console.log(method+': getUserContext failed: ',err);}); + }); + } +}; diff --git a/Chapter11/controller/restapi/router.js b/Chapter11/controller/restapi/router.js index 6fa15bd..14883e7 100644 --- a/Chapter11/controller/restapi/router.js +++ b/Chapter11/controller/restapi/router.js @@ -25,13 +25,15 @@ let hlcAdmin = require('./features/composer/hlcAdmin'); let hlcClient = require('./features/composer/hlcClient'); let setup = require('./features/composer/autoLoad'); let hlcFabric = require('./features/composer/queryBlockChain'); -router.post('/setup/autoLoad*', setup.autoLoad); -router.get('/setup/getPort*', setup.getPort); + router.get('/fabric/getChainInfo', hlcFabric.getChainInfo); router.get('/fabric/getChainEvents', hlcFabric.getChainEvents); router.get('/fabric/getHistory', hlcAdmin.getHistory); +router.post('/setup/autoLoad*', setup.autoLoad); +router.get('/composer/client/initEventRegistry*', hlcClient.init_z2bEvents); + module.exports = router; let count = 0; /** @@ -71,6 +73,7 @@ router.get('/composer/admin/getAllProfiles*', hlcAdmin.getAllProfiles); router.get('/composer/admin/listAsAdmin*', hlcAdmin.listAsAdmin); router.get('/composer/admin/getRegistries*', hlcAdmin.getRegistries); + router.post('/composer/admin/createProfile*', hlcAdmin.createProfile); router.post('/composer/admin/deleteProfile*', hlcAdmin.deleteProfile); router.post('/composer/admin/deploy*', hlcAdmin.deploy); @@ -90,6 +93,7 @@ router.post('/composer/admin/checkCard*', hlcAdmin.checkCard); router.post('/composer/admin/createCard*', hlcAdmin.createCard); router.post('/composer/admin/issueIdentity*', hlcAdmin.issueIdentity); + // router requests specific to the Buyer router.get('/composer/client/getItemTable*', hlcClient.getItemTable); router.post('/composer/client/getMyOrders*', hlcClient.getMyOrders); diff --git a/Chapter11/favicon.ico b/Chapter11/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter11/favicon.ico and /dev/null differ diff --git a/Chapter11/index.js b/Chapter11/index.js index 70319d6..cf79cb7 100644 --- a/Chapter11/index.js +++ b/Chapter11/index.js @@ -14,25 +14,28 @@ /* * Zero to Blockchain */ -var express = require('express'); -var http = require('http'); -var https = require('https'); -var path = require('path'); -var fs = require('fs'); -var mime = require('mime'); -var bodyParser = require('body-parser'); -var cfenv = require('cfenv'); -var cookieParser = require('cookie-parser'); -var session = require('express-session'); +'use strict'; +const express = require('express'); +const http = require('http'); +const ws = require('websocket').server; +// const https = require('https'); +const path = require('path'); +const fs = require('fs'); +const mime = require('mime'); +const bodyParser = require('body-parser'); +const cfenv = require('cfenv'); -var vcapServices = require('vcap_services'); -var uuid = require('uuid'); -var env = require('./controller/envV2.json'); -var sessionSecret = env.sessionSecret; -var appEnv = cfenv.getAppEnv(); -var app = express(); -var busboy = require('connect-busboy'); +const cookieParser = require('cookie-parser'); +// const session = require('express-session'); + +// const vcapServices = require('vcap_services'); +// const uuid = require('uuid'); +const env = require('./controller/envV2.json'); +const sessionSecret = env.sessionSecret; +const appEnv = cfenv.getAppEnv(); +const app = express(); +const busboy = require('connect-busboy'); app.use(busboy()); // the session secret is a text string of arbitrary length which is @@ -49,7 +52,8 @@ app.use(cookieParser(sessionSecret)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); -app.set('appName', 'z2b-chapter07'); +app.set('appName', 'z2b-chapter12'); +process.title = 'Z2B-C12'; app.set('port', appEnv.port); app.set('views', path.join(__dirname + '/HTML')); @@ -59,14 +63,58 @@ app.use(express.static(__dirname + '/HTML')); app.use(bodyParser.json()); // Define your own router file in controller folder, export the router, add it into the index.js. -// app.use('/', require("./controller/yourOwnRouter")); -app.use('/', require("./controller/restapi/router")); +app.use('/', require('./controller/restapi/router')); + +let server = http.createServer(); +let clients = []; +app.locals.index=-1; +/** + * WebSocket server + */ +app.locals.wsServer = new ws({httpServer: server}); +app.locals.wsServer.on('request', function(request) +{ + // create a connection back to the requestor + app.locals.connection = request.accept(null, request.origin); + // we need to know client index to remove them on 'close' event + app.locals.index = clients.push(app.locals.connection) - 1; + // save the newly created connection. This is so that we can support many connections to many browsers simultaneously + console.log((new Date()) + ' Connection accepted.'); + app.locals.connection.on('message', function(message) + { let obj ={ime: (new Date()).getTime(),text: message.utf8Data}; + // broadcast message to all connected clients + let json = JSON.stringify({ type:'Message', data: obj }); + app.locals.processMessages(json); + }); + + // user disconnected + app.locals.connection.on('close', function(_conn) { + console.log((new Date()) + ' Peer '+ app.locals.connection.socket._peername.address+':'+app.locals.connection.socket._peername.port+' disconnected with reason code: "'+_conn+'".'); + // remove user from the list of connected clients + // each browser connection has a unique address and socket combination + // When a browser session is disconnected, remove it from the array so we don't waste processing time sending messages to empty queues. + for (let each in clients) + {(function(_idx, _arr) + {if ((_arr[_idx].socket._peername.address === app.locals.connection.socket._peername.address) && (_arr[_idx].socket._peername.port === app.locals.connection.socket._peername.port)) + {clients.splice(_idx, 1);} + })(each, clients);} + }); +}); -if (cfenv.getAppEnv().isLocal == true) - { var server = app.listen(app.get('port'), function() {console.log('Listening locally on port %d', server.address().port);}); } - else - { var server = app.listen(app.get('port'), function() {console.log('Listening remotely on port %d', server.address().port);}); } +/** + * callable function to send messages over web socket + * @param {JSON} _jsonMsg - json formatted content to be sent as message data + */ +function processMessages (_jsonMsg) +{ + for (let i=0; i < clients.length; i++) {clients[i].send(JSON.stringify(_jsonMsg));} +} +// make the processMessages function available to all modules in this app. +app.locals.processMessages = processMessages; +// now set up the http server +server.on( 'request', app ); +server.listen(appEnv.port, function() {console.log('Listening locally on port %d', server.address().port);}); /** * load any file requested on the server * @param {express.req} req - the inbound request object from the client @@ -74,16 +122,16 @@ if (cfenv.getAppEnv().isLocal == true) * @function */ function loadSelectedFile(req, res) { - var uri = req.originalUrl; - var filename = __dirname + "/HTML" + uri; + let uri = req.originalUrl; + let filename = __dirname + '/HTML' + uri; fs.readFile(filename, function(err, data) { if (err) { console.log('Error loading ' + filename + ' error: ' + err); return res.status(500).send('Error loading ' + filename); } - var type = mime.lookup(filename); - res.setHeader('content-type', type); + let type = mime.lookup(filename); + res.setHeader('content-type', type); res.writeHead(200); res.end(data); }); diff --git a/Chapter11/network/lib/sample.js b/Chapter11/network/lib/sample.js index ddb951a..0d948b6 100644 --- a/Chapter11/network/lib/sample.js +++ b/Chapter11/network/lib/sample.js @@ -104,7 +104,7 @@ function OrderFromSupplier(purchase) { * @transaction */ function RequestShipping(purchase) { - if (purchase.order.status == JSON.stringify(orderStatus.Ordered)) + if ((purchase.order.status == JSON.stringify(orderStatus.Ordered)) || (purchase.order.status == JSON.stringify(orderStatus.Backordered))) { purchase.order.shipper = purchase.shipper; purchase.order.requestShipment = new Date().toISOString(); @@ -159,11 +159,11 @@ function RequestPayment(purchase) { {purchase.order.status = JSON.stringify(orderStatus.PayRequest); purchase.order.financeCo = purchase.financeCo; purchase.order.paymentRequested = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -174,11 +174,11 @@ function AuthorizePayment(purchase) { if ((JSON.parse(purchase.order.status).text == orderStatus.PayRequest.text ) || (JSON.parse(purchase.order.status).text == orderStatus.Resolve.text )) {purchase.order.status = JSON.stringify(orderStatus.Authorize); purchase.order.approved = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a payment to the seller @@ -189,11 +189,11 @@ function Pay(purchase) { if (JSON.parse(purchase.order.status).text == orderStatus.Authorize.text ) {purchase.order.status = JSON.stringify(orderStatus.Paid); purchase.order.paid = new Date().toISOString(); - } - return getAssetRegistry('org.acme.Z2BTestNetwork.Order') - .then(function (assetRegistry) { - return assetRegistry.update(purchase.order); - }); + return getAssetRegistry('org.acme.Z2BTestNetwork.Order') + .then(function (assetRegistry) { + return assetRegistry.update(purchase.order); + }); + } } /** * Record a dispute by the buyer diff --git a/Chapter12/Documentation/answers/composer/hlcClient_complete.js b/Chapter12/Documentation/answers/composer/hlcClient_complete.js index b1c4e1d..1bc701e 100644 --- a/Chapter12/Documentation/answers/composer/hlcClient_complete.js +++ b/Chapter12/Documentation/answers/composer/hlcClient_complete.js @@ -245,7 +245,7 @@ exports.orderAction = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(' retrying assetRegistry.update for: '+req.body.orderNo); - svc.loadTransaction(svc.m_connection, updateOrder, req.body.orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, updateOrder, req.body.orderNo, businessNetworkConnection); } else {console.log(req.body.orderNo+' submitTransaction to update status to '+req.body.action+' failed with text: ',error.message);} @@ -330,7 +330,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else {console.log(orderNo+' submitTransaction failed with text: ',error.message);} @@ -339,7 +339,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else { @@ -354,46 +354,11 @@ exports.addOrder = function (req, res, next) { }); }) .catch((error) => { - console.log(orderNo+' business network connection failed: text',error.message); + console.log(method + ' : '+orderNo+' business network connection failed: text',error.message); res.send({'result': 'failed', 'error':' order '+orderNo+' add failed on on business network connection '+error.message}); }); }; -/** - * Register for all of the available Z2BEvents - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * @returns {Object} - returns are via res.send -*/ -exports.init_z2bEvents = function (req, res, next) -{ - let method = 'init_z2bEvents'; - if (bRegistered) {res.send('Already Registered');} - else{ - bRegistered = true; - let _conn = svc.createAlertSocket(); - let businessNetworkConnection; - businessNetworkConnection = new BusinessNetworkConnection(); - businessNetworkConnection.setMaxListeners(50); - // - // v0.14 - // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) - // - // v0.15 - return businessNetworkConnection.connect(config.composer.adminCard) - .then(() => { - // using the businessNetworkConnection, start monitoring for events. - // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information - businessNetworkConnection.on('event', (event) => {_monitor(svc.al_connection, svc.f_connection, event); }); - res.send('event registration complete'); - }).catch((error) => { - // if an error is encountered, log the error and send it back to the requestor - console.log(method+' business network connection failed'+error.message); - res.send(method+' business network connection failed'+error.message); - }); - } -}; /** * _monitor * @param {WebSocket} _conn - web socket to use for member event posting @@ -401,7 +366,7 @@ exports.init_z2bEvents = function (req, res, next) * @param {Event} _event - the event just emitted * */ -function _monitor(_conn, _f_conn, _event) +function _monitor(locals, _event) { let method = '_monitor'; console.log(method+ ' _event received: '+_event.$type+' for Order: '+_event.orderID); @@ -411,7 +376,7 @@ function _monitor(_conn, _f_conn, _event) event.type = _event.$type; event.orderID = _event.orderID; event.ID = _event.buyerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); // using switch/case logic, send events back to each participant who should be notified. // for example, when a seller requests payment, they should be notified when the transaction has completed @@ -426,49 +391,85 @@ function _monitor(_conn, _f_conn, _event) case 'Bought': case 'PaymentRequested': event.ID = _event.sellerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); event.ID = _event.financeCoID; - _f_conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); break; case 'Ordered': case 'Cancelled': case 'Backordered': event.ID = _event.sellerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); event.ID = _event.providerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); break; case 'ShipRequest': case 'DeliveryStarted': case 'DeliveryCompleted': event.ID = _event.sellerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); event.ID = _event.providerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); event.ID = _event.shipperID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); break; case 'DisputeOpened': case 'Resolved': case 'Refunded': case 'Paid': event.ID = _event.sellerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); event.ID = _event.providerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); event.ID = _event.shipperID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); event.ID = _event.financeCoID; - _f_conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); break; case 'PaymentAuthorized': event.ID = _event.sellerID; - _conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); event.ID = _event.financeCoID; - _f_conn.sendUTF(JSON.stringify(event)); + svc.send(locals, 'Alert',JSON.stringify(event)); break; default: break; } -} \ No newline at end of file +} + +/** + * Register for all of the available Z2BEvents + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + * @returns {Object} - returns are via res.send +*/ +exports.init_z2bEvents = function (req, res, next) +{ + let method = 'init_z2bEvents'; + if (bRegistered) {res.send('Already Registered');} + else{ + bRegistered = true; +// svc.createAlertSocket(); + let businessNetworkConnection; + businessNetworkConnection = new BusinessNetworkConnection(); + businessNetworkConnection.setMaxListeners(50); + // + // v0.14 + // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // + // v0.15 + return businessNetworkConnection.connect(config.composer.adminCard) + .then(() => { + // using the businessNetworkConnection, start monitoring for events. + // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information + businessNetworkConnection.on('event', (event) => {_monitor(req.app.locals, event); }); + res.send('event registration complete'); + }).catch((error) => { + // if an error is encountered, log the error and send it back to the requestor + console.log(method+' business network connection failed'+error.message); + res.send(method+' business network connection failed'+error.message); + }); + } +}; diff --git a/Chapter12/Documentation/answers/js/z2b-buyer_complete.js b/Chapter12/Documentation/answers/js/z2b-buyer_complete.js index 49d7795..0beb896 100644 --- a/Chapter12/Documentation/answers/js/z2b-buyer_complete.js +++ b/Chapter12/Documentation/answers/js/z2b-buyer_complete.js @@ -32,22 +32,20 @@ function loadBuyerUX () { // get the html page to load let toLoad = 'buyer.html'; - // get the port to use for web socket communications with the server - getPort(); // if (buyers.length === 0) then autoLoad() was not successfully run before this web app starts, so the sie of the buyer list is zero // assume user has run autoLoad and rebuild member list // if autoLoad not yet run, then member list length will still be zero if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupBuyer(page[0], port[0]);}); - } - else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupBuyer(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupBuyer(page);}); + } + else{ + $.when($.get(toLoad)).done(function (page) + {setupBuyer(page);}); } } -function setupBuyer(page, port) +function setupBuyer(page) { // empty the hetml element that will hold this page $('#buyerbody').empty(); @@ -60,9 +58,6 @@ function setupBuyer(page, port) else {$(b_notify).removeClass('off'); $(b_notify).addClass('on'); } // update the text on the page using the prompt data for the selected language updatePage('buyer'); - msgPort = port.port; - // connect to the web socket and tell the web socket where to display messages - wsDisplay('buyer_messages', msgPort); // enable the buttons to process an onClick event let _create = $('#newOrder'); let _list = $('#orderStatus'); @@ -120,7 +115,7 @@ function displayOrderForm() $('#amount').append('$'+totalAmount+'.00'); // build a select list for the items let _str = ''; - for (let each in itemTable){(function(_idx, _arr){_str+=''})(each, itemTable)} + for (let each in itemTable){(function(_idx, _arr){_str+='';})(each, itemTable);} $('#items').empty(); $('#items').append(_str); $('#cancelNewOrder').on('click', function (){_orderDiv.empty();}); diff --git a/Chapter12/Documentation/answers/js/z2b-events_complete.js b/Chapter12/Documentation/answers/js/z2b-events_complete.js index 44c5ef5..282f3ea 100644 --- a/Chapter12/Documentation/answers/js/z2b-events_complete.js +++ b/Chapter12/Documentation/answers/js/z2b-events_complete.js @@ -16,8 +16,7 @@ 'use strict'; -let alertPort = null; -let financeAlertPort = null; +let wsSocket; /** * load the four initial user roles into a single page. @@ -26,8 +25,8 @@ function singleUX () { let toLoad = 'singleUX.html'; if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (_page, _port, _res) - { msgPort = _port.port; + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { $('#body').empty(); $('#body').append(_page); loadBuyerUX(); @@ -85,8 +84,8 @@ function memberLoad () */ function dropDummy(_in) { - let _a = new Array() - for (let each in _in){(function(_idx, _arr){console.log('_arr['+_idx+'].id is: '+_arr[_idx].id); if (_arr[_idx].id !== 'noop@dummy')_a.push(_arr[_idx]);})(each, _in);} + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} return _a; } /** @@ -136,61 +135,17 @@ function _getMembers(_members) */ function goEventInitialize() { - $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log(_res);}) -} - -/** - * get the alert web socket port - */ -function getAlertPort () -{ - if (alertPort === null) - { - $.when($.get('/setup/getAlertPort')).done(function (port) - { - console.log('alert port is: '+port.port); alertPort = port.port; - let wsSocket = new WebSocket('ws://localhost:'+alertPort); - wsSocket.onopen = function () {wsSocket.send('connected to alerts');}; - wsSocket.onmessage = function (message) { - console.log(message.data); - let event = JSON.parse(message.data); - addNotification(event.type, event.ID, event.orderID); - }; - wsSocket.onerror = function (error) {console.log('Alert Socket error on wsSocket: ' + error);}; - }); - } -} -/** - * get the finance alert web socket port - */ -function getFinanceAlertPort () -{ - if (financeAlertPort === null) - { - $.when($.get('/setup/getFinanceAlertPort')).done(function (port) - { - console.log('finance alert port is: '+port.port); financeAlertPort = port.port; - let wsSocket = new WebSocket('ws://localhost:'+financeAlertPort); - wsSocket.onopen = function () {wsSocket.send('connected to finance alerts');}; - wsSocket.onmessage = function (message) { - console.log(message.data); - let event = JSON.parse(message.data); - addNotification(event.type, event.ID, event.orderID); - }; - wsSocket.onerror = function (error) {console.log('Finance Alert Socket error on wsSocket: ' + error);}; - }); - } + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); } /** - * * @param {Event} _event - inbound Event * @param {String} _id - subscriber target * @param {String} _orderID - inbound order id */ function addNotification(_event, _id, _orderID) { - let method = 'showNotification'; + let method = 'addNotification'; console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); let type = getSubscriber(_id); if (type === 'none') {return;} @@ -277,4 +232,52 @@ function notifyMe (_alerts, _id) let b_h = false; for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter12/Documentation/answers/js/z2b-financeCo_complete.js b/Chapter12/Documentation/answers/js/z2b-financeCo_complete.js index e0c3685..40ff08e 100644 --- a/Chapter12/Documentation/answers/js/z2b-financeCo_complete.js +++ b/Chapter12/Documentation/answers/js/z2b-financeCo_complete.js @@ -31,22 +31,19 @@ let f_alerts; function loadFinanceCoUX () { let toLoad = 'financeCo.html'; - // get the FinanceAlert Port - getFinanceAlertPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupFinanceCo(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupFinanceCo(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupFinanceCo(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupFinanceCo(page);}); } } /** * @param {String} page HTML page to load - * @param {Integer} port Websocket port to use */ -function setupFinanceCo(page, port) +function setupFinanceCo(page) { $('#body').empty(); $('#body').append(page); @@ -56,9 +53,6 @@ function setupFinanceCo(page, port) else {$(f_notify).removeClass('off'); $(f_notify).addClass('on'); } updatePage( 'financeCo'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('finance_messages', msgPort); let _clear = $('#financeCOclear'); let _list = $('#financeCOorderStatus'); let _orderDiv = $('#'+financeCOorderDiv); diff --git a/Chapter12/Documentation/answers/network/lib/sample_complete.js b/Chapter12/Documentation/answers/network/lib/sample_complete.js index 8a4ef40..7a0c946 100644 --- a/Chapter12/Documentation/answers/network/lib/sample_complete.js +++ b/Chapter12/Documentation/answers/network/lib/sample_complete.js @@ -81,7 +81,7 @@ function Buy(purchase) { * @transaction */ function OrderCancel(purchase) { - if ((purchase.order.status == JSON.stringify(orderStatus.Created)) || (purchase.order.status == JSON.stringify(orderStatus.Bought))) + if ((purchase.order.status == JSON.stringify(orderStatus.Created)) || (purchase.order.status == JSON.stringify(orderStatus.Bought)) || (purchase.order.status == JSON.stringify(orderStatus.Backordered))) { purchase.order.buyer = purchase.buyer; purchase.order.seller = purchase.seller; @@ -126,7 +126,7 @@ function OrderFromSupplier(purchase) { * @transaction */ function RequestShipping(purchase) { - if (purchase.order.status == JSON.stringify(orderStatus.Ordered)) + if ((purchase.order.status == JSON.stringify(orderStatus.Ordered)) || (purchase.order.status == JSON.stringify(orderStatus.Backordered))) { purchase.order.shipper = purchase.shipper; purchase.order.requestShipment = new Date().toISOString(); diff --git a/Chapter12/HTML/favicon.ico b/Chapter12/HTML/favicon.ico old mode 100755 new mode 100644 index fc9e25d..3dbe425 Binary files a/Chapter12/HTML/favicon.ico and b/Chapter12/HTML/favicon.ico differ diff --git a/Chapter12/HTML/js/z2b-admin.js b/Chapter12/HTML/js/z2b-admin.js index 67f421a..f3c3ffc 100644 --- a/Chapter12/HTML/js/z2b-admin.js +++ b/Chapter12/HTML/js/z2b-admin.js @@ -18,7 +18,6 @@ let creds; let connection; -let msgPort = null; let _blctr = 0; /** @@ -34,19 +33,6 @@ function loadAdminUX () listMemRegistries(); }); } -/** - * connect to the provided web socket - * @param {String} _target - location to post messages - * @param {Integer} _port - web socket port # - */ -function wsDisplay(_target, _port) -{ - let content = $('#'+_target); - let wsSocket = new WebSocket('ws://localhost:'+_port); - wsSocket.onopen = function () {wsSocket.send('connected to client');}; - wsSocket.onmessage = function (message) {content.append(formatMessage(message.data));}; - wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ' + error);}; -} /** * list the available business networks */ @@ -361,7 +347,7 @@ function preLoad() $('#body').empty(); let options = {}; $.when($.post('/setup/autoLoad', options)).done(function (_results) - { msgPort = _results.port; wsDisplay('body', msgPort); }); + { console.log('Autoload Initiated'); $('#body').append('

    Autoload Initiated

    '); }); } /** @@ -754,28 +740,9 @@ function getHistorian() */ function getChainEvents() { - $.when($.get('fabric/getChainEvents')).done(function(_res) - { let _str = '

    Get Chain events requested. Sending to port: '+_res.port+'

    '; - let content = $('#blockchain'); - let csSocket = new WebSocket('ws://localhost:'+_res.port); - csSocket.onopen = function () {csSocket.send('connected to client');}; - csSocket.onmessage = function (message) { - _blctr ++; - if (message.data !== 'connected') - {$(content).append('block '+JSON.parse(message.data).header.number+'
    Hash: '+JSON.parse(message.data).header.data_hash+'
    '); - if (_blctr > 4) {let leftPos = $(content).scrollLeft(); $(content).animate({scrollLeft: leftPos + 300}, 250);} - } - }; - csSocket.onerror = function (error) {console.log('WebSocket error: ' + error);}; - $('#admin-forms').empty(); - $('#admin-forms').append(_str); + $.when($.get('/fabric/getChainEvents')).done(function(_res) + { $('#body').append('

    Get Chain events requested.

    '); + let _host = (host_address.slice(0,9) === 'localhost') ? 'localhost' : host_address; + console.log('getChainEvents host_address: '+_host); }); -} -/** - * display blockchain updates - */ -function displayAdminUpdate() -{ - let toLoad = 'adminHelp.html'; - $.when($.get(toLoad)).done(function(_page){$('#admin-forms').empty(); $('#admin-forms').append(_page);}); } \ No newline at end of file diff --git a/Chapter12/HTML/js/z2b-buyer.js b/Chapter12/HTML/js/z2b-buyer.js index 38cb645..793ff73 100644 --- a/Chapter12/HTML/js/z2b-buyer.js +++ b/Chapter12/HTML/js/z2b-buyer.js @@ -32,39 +32,32 @@ function loadBuyerUX () { // get the html page to load let toLoad = 'buyer.html'; - // get the port to use for web socket communications with the server - getPort(); // if (buyers.length === 0) then autoLoad() was not successfully run before this web app starts, so the sie of the buyer list is zero // assume user has run autoLoad and rebuild member list // if autoLoad not yet run, then member list length will still be zero if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupBuyer(page[0], port[0]);}); - } - else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupBuyer(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupBuyer(page);}); + } + else{ + $.when($.get(toLoad)).done(function (page) + {setupBuyer(page);}); + } } -} - -function setupBuyer(page, port) -{ + + function setupBuyer(page) + { // empty the hetml element that will hold this page $('#buyerbody').empty(); $('#buyerbody').append(page); // empty the buyer alerts array - // =====> Your Code Goes Here <========= + b_alerts = []; // if there are no alerts, then remove the 'on' class and add the 'off' class if (b_alerts.length === 0) - { - // =====> Your Code Goes Here <========= - } + {$(b_notify).removeClass('on'); $(b_notify).addClass('off'); } else {$(b_notify).removeClass('off'); $(b_notify).addClass('on'); } // update the text on the page using the prompt data for the selected language updatePage('buyer'); - msgPort = port.port; - // connect to the web socket and tell the web socket where to display messages - wsDisplay('buyer_messages', msgPort); // enable the buttons to process an onClick event let _create = $('#newOrder'); let _list = $('#orderStatus'); @@ -80,20 +73,20 @@ function setupBuyer(page, port) // display the name of the current buyer $('#company')[0].innerText = buyers[0].companyName; // save the current buyer id as b_id - // =====> Your Code Goes Here <========= + b_id = buyers[0].id; // subscribe to events - // =====> Your Code Goes Here <========= + z2bSubscribe('Buyer', b_id); // create a function to execute when the user selects a different buyer $('#buyer').on('change', function() { _orderDiv.empty(); $('#buyer_messages').empty(); $('#company')[0].innerText = findMember($('#buyer').find(':selected').text(),buyers).companyName; // unsubscribe the current buyer - // =====> Your Code Goes Here <========= + z2bUnSubscribe(b_id); // get the new buyer id - // =====> Your Code Goes Here <========= + b_id = findMember($('#buyer').find(':selected').text(),buyers).id; // subscribe the new buyer - // =====> Your Code Goes Here <========= -}); + z2bSubscribe('Buyer', b_id); + }); } /** @@ -122,7 +115,7 @@ function displayOrderForm() $('#amount').append('$'+totalAmount+'.00'); // build a select list for the items let _str = ''; - for (let each in itemTable){(function(_idx, _arr){_str+=''})(each, itemTable)} + for (let each in itemTable){(function(_idx, _arr){_str+='';})(each, itemTable);} $('#items').empty(); $('#items').append(_str); $('#cancelNewOrder').on('click', function (){_orderDiv.empty();}); @@ -326,11 +319,11 @@ function formatOrders(_target, _orders) }); // use the notifyMe function to determine if this order is in the alert array. // if it is, the highlight the $('#b_status'+_idx) html element by adding the 'highlight' class - // =====> Your Code Goes Here <========= -})(each, _orders); + if (notifyMe(b_alerts, _arr[_idx].id)) {$('#b_status'+_idx).addClass('highlight'); } + })(each, _orders); } // reset the b_alerts array to a new array b_alerts = new Array(); // call the toggleAlerts function to reset the alert icon - // =====> Your Code Goes Here <========= + toggleAlert($('#buyer_notify'), b_alerts, b_alerts.length); } \ No newline at end of file diff --git a/Chapter12/HTML/js/z2b-events.js b/Chapter12/HTML/js/z2b-events.js index fad87fa..282f3ea 100644 --- a/Chapter12/HTML/js/z2b-events.js +++ b/Chapter12/HTML/js/z2b-events.js @@ -16,8 +16,7 @@ 'use strict'; -let alertPort = null; -let financeAlertPort = null; +let wsSocket; /** * load the four initial user roles into a single page. @@ -26,8 +25,8 @@ function singleUX () { let toLoad = 'singleUX.html'; if ((typeof(buyers) === 'undefined') || (buyers === null) || (buyers.length === 0)) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (_page, _port, _res) - { msgPort = _port.port; + { $.when($.get(toLoad), deferredMemberLoad()).done(function (_page, _res) + { $('#body').empty(); $('#body').append(_page); loadBuyerUX(); @@ -35,8 +34,8 @@ function singleUX () loadProviderUX(); loadShipperUX(); // Initialize Registration for all Z2B Business Events - // =====> Your Code Goes Here <========= -}); + goEventInitialize(); + }); } else{ $.when($.get(toLoad)).done(function(_page) @@ -48,8 +47,8 @@ function singleUX () loadProviderUX(); loadShipperUX(); // Initialize Registration for all Z2B Business Events - // =====> Your Code Goes Here <========= -}); + goEventInitialize(); + }); } } /** @@ -85,8 +84,8 @@ function memberLoad () */ function dropDummy(_in) { - let _a = new Array() - for (let each in _in){(function(_idx, _arr){console.log('_arr['+_idx+'].id is: '+_arr[_idx].id); if (_arr[_idx].id !== 'noop@dummy')_a.push(_arr[_idx]);})(each, _in);} + let _a = new Array(); + for (let each in _in){(function(_idx, _arr){if (_arr[_idx].id.slice(0,10) !== 'noop@dummy'){_a.push(_arr[_idx]);}})(each, _in);} return _a; } /** @@ -136,61 +135,17 @@ function _getMembers(_members) */ function goEventInitialize() { - $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log(_res);}) + $.when($.get('/composer/client/initEventRegistry')).done(function(_res){console.log('getChainEvents results: ', _res);}); } /** - * get the alert web socket port - */ -function getAlertPort () -{ - if (alertPort === null) - { - $.when($.get('/setup/getAlertPort')).done(function (port) - { - console.log('alert port is: '+port.port); alertPort = port.port; - let wsSocket = new WebSocket('ws://localhost:'+alertPort); - wsSocket.onopen = function () {wsSocket.send('connected to alerts');}; - wsSocket.onmessage = function (message) { - console.log(message.data); - let event = JSON.parse(message.data); - addNotification(event.type, event.ID, event.orderID); - }; - wsSocket.onerror = function (error) {console.log('Alert Socket error on wsSocket: ' + error);}; - }); - } -} -/** - * get the finance alert web socket port - */ -function getFinanceAlertPort () -{ - if (financeAlertPort === null) - { - $.when($.get('/setup/getFinanceAlertPort')).done(function (port) - { - console.log('finance alert port is: '+port.port); financeAlertPort = port.port; - let wsSocket = new WebSocket('ws://localhost:'+financeAlertPort); - wsSocket.onopen = function () {wsSocket.send('connected to finance alerts');}; - wsSocket.onmessage = function (message) { - console.log(message.data); - let event = JSON.parse(message.data); - addNotification(event.type, event.ID, event.orderID); - }; - wsSocket.onerror = function (error) {console.log('Finance Alert Socket error on wsSocket: ' + error);}; - }); - } -} - -/** - * * @param {Event} _event - inbound Event * @param {String} _id - subscriber target * @param {String} _orderID - inbound order id */ function addNotification(_event, _id, _orderID) { - let method = 'showNotification'; + let method = 'addNotification'; console.log(method+' _event'+_event+' id: '+_id+' orderID: '+_orderID); let type = getSubscriber(_id); if (type === 'none') {return;} @@ -277,4 +232,52 @@ function notifyMe (_alerts, _id) let b_h = false; for (let each in _alerts) {(function(_idx, _arr){if (_id === _arr[_idx].order){b_h = true;}})(each, _alerts);} return b_h; +} +/** + * connect to web socket + */ +function wsConnect() +{ + let method = 'wsConnect'; + if (!window.WebSocket) {console.log('this browser does not support web sockets');} + let content = $('#body'); + let blockchain = $('#blockchain'); + // updated from ws: to wss: to support access over https + if (host_address.slice(0,9) === 'localhost') + { + wsSocket = new WebSocket('ws://'+host_address); + }else + { + wsSocket = new WebSocket('wss://'+host_address); + } + wsSocket.onerror = function (error) {console.log('WebSocket error on wsSocket: ', error);}; + wsSocket.onopen = function () + {console.log ('connect.onOpen initiated to: '+host_address); wsSocket.send('connected to client');}; + wsSocket.onmessage = function (message) + { + let incoming + incoming = message.data; + // console.log(method+ ' incoming is: '+incoming); + while (incoming instanceof Object === false){incoming = JSON.parse(incoming);} + switch (incoming.type) + { + case 'Message': + content.append(formatMessage(incoming.data)); + break; + case 'Alert': + let event = JSON.parse(incoming.data); + addNotification(event.type, event.ID, event.orderID); + break; + case 'BlockChain': + _blctr ++; + if (incoming.data !== 'connected') + { + $(blockchain).append('block '+incoming.data.header.number+'
    Hash: '+incoming.data.header.data_hash+'
    '); + if (_blctr > 4) {let leftPos = $(blockchain).scrollLeft(); $(blockchain).animate({scrollLeft: leftPos + 300}, 250);} + } + break; + default: + console.log('Can Not Process message type: ',incoming.type); + } + }; } \ No newline at end of file diff --git a/Chapter12/HTML/js/z2b-financeCo.js b/Chapter12/HTML/js/z2b-financeCo.js index 703b3e2..40ff08e 100644 --- a/Chapter12/HTML/js/z2b-financeCo.js +++ b/Chapter12/HTML/js/z2b-financeCo.js @@ -31,22 +31,19 @@ let f_alerts; function loadFinanceCoUX () { let toLoad = 'financeCo.html'; - // get the FinanceAlert Port - getFinanceAlertPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupFinanceCo(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupFinanceCo(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupFinanceCo(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupFinanceCo(page);}); } } /** * @param {String} page HTML page to load - * @param {Integer} port Websocket port to use */ -function setupFinanceCo(page, port) +function setupFinanceCo(page) { $('#body').empty(); $('#body').append(page); @@ -56,9 +53,6 @@ function setupFinanceCo(page, port) else {$(f_notify).removeClass('off'); $(f_notify).addClass('on'); } updatePage( 'financeCo'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('finance_messages', msgPort); let _clear = $('#financeCOclear'); let _list = $('#financeCOorderStatus'); let _orderDiv = $('#'+financeCOorderDiv); @@ -157,7 +151,9 @@ function formatFinanceOrders(_target, _orders) let _button = '' _action += ''; if (_idx > 0) {_str += '
    ';} - _str += '
    '+textPrompts.orderProcess.itemno+''+textPrompts.orderProcess.description+''+textPrompts.orderProcess.qty+''+textPrompts.orderProcess.price+'
    "+_curObj+""+_arr[_idx][_curObj]+"
    "+_curObj[0]+""+_curObj2+""+_arr2[_idx2][_curObj2[0]]+"
    '+_curObj+''+_arr[_idx][_curObj]+'
    '+_curObj[0]+''+_curObj2+''+_arr2[_idx2][_curObj2[0]]+'
    '; + let _len = 'resource:org.acme.Z2BTestNetwork.Buyer#'.length; + let _buyer = _arr[_idx].buyer.substring(_len, _arr[_idx].buyer.length); + _str += '
    Order #StatusTotalBuyer: '+findMember(_arr[_idx].buyer,buyers).companyName+'
    '; _str += ''+_action+''+_button+'
    Order #StatusTotalBuyer: '+findMember(_buyer,buyers).companyName+'
    '+_arr[_idx].id+''+JSON.parse(_arr[_idx].status).text+': '+_date+'$'+_arr[_idx].amount+'.00
    '; _str+= formatDetail(_idx, _arr[_idx]); })(each, _orders); diff --git a/Chapter12/HTML/js/z2b-initiate.js b/Chapter12/HTML/js/z2b-initiate.js index 3fcfe09..7ba4493 100644 --- a/Chapter12/HTML/js/z2b-initiate.js +++ b/Chapter12/HTML/js/z2b-initiate.js @@ -20,6 +20,8 @@ let connectionProfileName = 'z2b-test-profile'; let networkFile = 'zerotoblockchain-network.bna'; let businessNetwork = 'zerotoblockchain-network'; +let host_address = window.location.host; + let buyers = new Array(); let sellers= new Array(); let providers= new Array(); @@ -58,7 +60,5 @@ function initPage () // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring getChainEvents(); // get the asynch port - getPort(); - // get the Alert Port - getAlertPort(); + wsConnect(); } diff --git a/Chapter12/HTML/js/z2b-provider.js b/Chapter12/HTML/js/z2b-provider.js index b849d89..cc8d752 100644 --- a/Chapter12/HTML/js/z2b-provider.js +++ b/Chapter12/HTML/js/z2b-provider.js @@ -28,23 +28,21 @@ let p_id; function loadProviderUX () { let toLoad = 'provider.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupProvider(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupProvider(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupProvider(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupProvider(page);}); } } /** * load the Provider User Experience * @param {String} page - the name of the page to load - * @param {Integer} port - the port number to use */ -function setupProvider(page, port) +function setupProvider(page) { $('#providerbody').empty(); $('#providerbody').append(page); @@ -52,9 +50,6 @@ function setupProvider(page, port) {$(p_notify).removeClass('on'); $(p_notify).addClass('off'); } else {$(p_notify).removeClass('off'); $(p_notify).addClass('on'); } updatePage('provider'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('provider_messages', msgPort); let _clear = $('#provider_clear'); let _list = $('#providerOrderStatus'); let _orderDiv = $('#'+providerOrderDiv); diff --git a/Chapter12/HTML/js/z2b-seller.js b/Chapter12/HTML/js/z2b-seller.js index 3a8fd29..333b45b 100644 --- a/Chapter12/HTML/js/z2b-seller.js +++ b/Chapter12/HTML/js/z2b-seller.js @@ -26,23 +26,21 @@ let s_id; function loadSellerUX () { let toLoad = 'seller.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupSeller(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupSeller(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupSeller(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupSeller(page);}); } } /** * load the administration User Experience * @param {String} page - page to load - * @param {Integer} port - web socket port to use */ -function setupSeller(page, port) +function setupSeller(page) { $('#sellerbody').empty(); $('#sellerbody').append(page); @@ -50,8 +48,6 @@ function setupSeller(page, port) {$(s_notify).removeClass('on'); $(s_notify).addClass('off'); } else {$(s_notify).removeClass('off'); $(s_notify).addClass('on'); } updatePage('seller'); - msgPort = port.port; - wsDisplay('seller_messages', msgPort); let _clear = $('#seller_clear'); let _list = $('#sellerOrderStatus'); let _orderDiv = $('#'+sellerOrderDiv); diff --git a/Chapter12/HTML/js/z2b-shipper.js b/Chapter12/HTML/js/z2b-shipper.js index 9746eb1..049d021 100644 --- a/Chapter12/HTML/js/z2b-shipper.js +++ b/Chapter12/HTML/js/z2b-shipper.js @@ -28,22 +28,20 @@ let sh_id; function loadShipperUX () { let toLoad = 'shipper.html'; - getPort(); if (buyers.length === 0) - { $.when($.get(toLoad), $.get('/setup/getPort'), deferredMemberLoad()).done(function (page, port, res) - {setupShipper(page[0], port[0]);}); + { $.when($.get(toLoad), deferredMemberLoad()).done(function (page, res) + {setupShipper(page[0]);}); } else{ - $.when($.get(toLoad), $.get('/setup/getPort')).done(function (page, port) - {setupShipper(page[0], port[0]);}); + $.when($.get(toLoad)).done(function (page) + {setupShipper(page);}); } } /** * * @param {String} page - the page to load - * @param {Integer} port - the web socket to use */ -function setupShipper(page, port) +function setupShipper(page) { $('#shipperbody').empty(); $('#shipperbody').append(page); @@ -51,9 +49,6 @@ function setupShipper(page, port) {$(sh_notify).removeClass('on'); $(sh_notify).addClass('off'); } else {$(sh_notify).removeClass('off'); $(sh_notify).addClass('on'); } updatePage('shipper'); - console.log('port is: '+port.port); - msgPort = port.port; - wsDisplay('shipper_messages', msgPort); let _clear = $('#shipper_clear'); let _list = $('#shipperOrderStatus'); let _orderDiv = $('#'+shipperOrderDiv); diff --git a/Chapter12/HTML/js/z2b-utilities.js b/Chapter12/HTML/js/z2b-utilities.js index 6072ca2..7f2c962 100644 --- a/Chapter12/HTML/js/z2b-utilities.js +++ b/Chapter12/HTML/js/z2b-utilities.js @@ -292,14 +292,6 @@ function displayAPI(_api) */ function formatMessage(_msg) {return '

    '+_msg+'

    ';} -/** - * get the web socket port - */ -function getPort () -{ - if (msgPort === null) - { $.when($.get('/setup/getPort')).done(function (port){console.log('port is: '+port.port); msgPort = port.port;});} -} /** * closes all accordians in this div @@ -340,4 +332,3 @@ function accToggle(_parent, _body, _header) $(parent).removeClass('off'); $(parent).addClass('on'); } } - diff --git a/Chapter12/controller/env.json b/Chapter12/controller/env.json index dd1c45d..72dc4a1 100644 --- a/Chapter12/controller/env.json +++ b/Chapter12/controller/env.json @@ -1,16 +1,4 @@ { - "composer": - { - "connectionProfile": "hlfv1", - "network": "zerotoblockchain-network", - "adminID": "admin", - "adminPW": "adminpw", - "PeerAdmin": "PeerAdmin", - "PeerPW": "randomString", - "NS": "org.acme.Z2BTestNetwork", - "adminCard": "admin@zerotoblockchain-network", - "PeerCard": "PeerAdmin@hlfv1" - }, "fabric": { "user": "queryUser", @@ -24,6 +12,18 @@ "ordererURL" : "grpc://localhost:7050", "caURL": "http://localhost:7054" }, + "composer": + { + "connectionProfile": "hlfv1", + "network": "zerotoblockchain-network", + "adminID": "admin", + "adminPW": "adminpw", + "PeerAdmin": "PeerAdmin", + "PeerPW": "randomString", + "NS": "org.acme.Z2BTestNetwork", + "adminCard": "admin@zerotoblockchain-network", + "PeerCard": "PeerAdmin@hlfv1" + }, "metaData": { "version": 1, "userName": "temp", @@ -31,6 +31,8 @@ "businessNetwork":"", "enrollmentSecret": "temp" }, + "keyValStore": "/.composer-credentials", + "kube_address":"169.46.111.109", "connectionProfile": { "name": "hlfv1", diff --git a/Chapter12/controller/restapi/features/composer/Z2B_Services.js b/Chapter12/controller/restapi/features/composer/Z2B_Services.js index 4367cf3..c4f8aa4 100644 --- a/Chapter12/controller/restapi/features/composer/Z2B_Services.js +++ b/Chapter12/controller/restapi/features/composer/Z2B_Services.js @@ -13,16 +13,18 @@ */ 'use strict'; -var fs = require('fs'); -var path = require('path'); +let fs = require('fs'); +let path = require('path'); const sleep = require('sleep'); -const ws = require('websocket'); -const http = require('http'); +// const ws = require('websocket'); +// const http = require('http'); +// const url = require('url'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); const appEnv = cfenv.getAppEnv(); +const util = require('./Z2B_Utilities'); app.set('port', appEnv.port); @@ -37,7 +39,7 @@ app.set('port', appEnv.port); * @class * @memberof module:Z2Blockchain */ -var Z2Blockchain = { +let Z2Blockchain = { /** * create an empty order. This is used by any server side routine that needs to create an new @@ -105,8 +107,8 @@ var Z2Blockchain = { /** * update item quantity. used by the autoLoad process. * @param {item_number} _itemNo - item number to find - * @param {vendor_array} _itemArray - item array from order * @param {item_number} _qty - quantity to change * @utility + * @param {vendor_array} _itemArray - item array from order */ setItem: function (_itemNo, _qty, _itemArray) { @@ -115,48 +117,78 @@ var Z2Blockchain = { }, /** * supplemental routine to resubmit orders when MVCC_READ_CONFLICT encountered + * @param {object} _con - web socket connection * @param {transaction} _item - transaction to process * @param {order_object} _id - order id * @param {BusinessNetworkConnection} businessNetworkConnection - already created business network connection + * @returns {promise} promise */ loadTransaction: function (_con, _item, _id, businessNetworkConnection) { - var method = 'loadTransaction'; + let method = 'loadTransaction'; return businessNetworkConnection.submitTransaction(_item) .then(() => { - console.log(method+': order '+_id+' successfully added '); - _con.sendUTF(method+': order '+_id+' successfully added'); + console.log(method+': order '+_id+' successfully added '); + this.send(_con, 'Message', 'Order '+_id+' successfully added'); }) .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) + if (error.message.search('MVCC_READ_CONFLICT') !== -1) {sleep.sleep(5); - console.log(_id+" loadTransaction retrying submit transaction for: "+_id); - this.loadTransaction(_con, _item, _id, businessNetworkConnection); + console.log(_id+' loadTransaction retrying submit transaction for: '+_id); + this.loadTransaction(_con, _item, _id, businessNetworkConnection); } }); }, /** * add an order to a registry. This adds an Asset and does not execute a transaction - * @param {order_object} _order - order_object to process - * @param {assetRegistry} _registry - registry into which asset (order) should be placed + * @param {order_object} _con - websocket + * @param {assetRegistry} _order - order_object to process + * @param {networkTransaction} _registry - registry into which asset (order) should be placed * @param {networkTransaction} _createNew - transaction to be processed after order successfully added - * @param {businessNetworkConnection} _bnc - business network connection to use */ + * @param {businessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ addOrder: function (_con, _order, _registry, _createNew, _bnc) - { - var method = 'addOrder'; - return _registry.add(_order) - .then(() => { - this.loadTransaction(_con, _createNew, _order.orderNumber, _bnc); - }) - .catch((error) => { - if (error.message.search('MVCC_READ_CONFLICT') != -1) - {console.log(_order.orderNumber+" addOrder retrying assetRegistry.add for: "+_order.orderNumber); +{ + let method = 'addOrder'; + return _registry.add(_order) + .then(() => { + this.loadTransaction(_con, _createNew, _order.orderNumber, _bnc); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(_order.orderNumber+' addOrder retrying assetRegistry.add for: '+_order.orderNumber); this.addOrder(_con, _order, _registry, _createNew, _bnc); - } - else {console.log(method+' error with assetRegistry.add', error)} - }); + } + else {console.log(method+' error with assetRegistry.add', error);} + }); }, +/** + * repeats the bind identity request + * @param {WebSocket} _con - order_object to process + * @param {String} _id - registry into which asset (order) should be placed + * @param {String} _cert - transaction to be processed after order successfully added + * @param {BusinessNetworkConnection} _bnc - business network connection to use + * @returns {promise} promise + */ +bindIdentity: function (_con, _id, _cert, _bnc) +{ + let method = 'bindIdentity'; + console.log(method+' retrying bindIdentity for: '+_id); + return _bnc.bindIdentity(_id, _cert) + .then(() => { + console.log(method+' Succeeded for: '+_id); + }) + .catch((error) => { + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log(' bindIdentity retrying _bnc.bindIdentity(_id, _cert) for: '+_id); + this.bindIdentity(_con, _id, _cert, _bnc); + } + else {console.log(method+' error with _bnc.bindIdentity(_id, _cert) for: '+_id+' with error: ', error);} + }); +}, + /** * saves the member table with ids and secrets * @param {array} _table - array of JSON objects to save to file @@ -168,23 +200,26 @@ addOrder: function (_con, _order, _registry, _createNew, _bnc) let _mem = '{"members": ['; for (let each in _table) {(function(_idx, _arr) - {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table)} + {if(_idx>0){_mem += ', ';} _mem +=JSON.stringify(_arr[_idx]);})(each, _table);} _mem += ']}'; fs.writeFileSync(newFile, _mem, options); }, /** * saves the item table * @param {array} _table - array of JSON objects to save to file + * @param {JSON} _table - data to be saved */ - saveItemTable: function (_table) - { - let options = { flag : 'w' }; - let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); - let _mem = '{"items": ['; - for (let each in _table) - {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table)} - _mem += ']}'; - fs.writeFileSync(newFile, _mem, options); - }, +saveItemTable: function (_table) +{ + console.log('_table: ', _table); + let options = { flag : 'w' }; + let newFile = path.join(path.dirname(require.main.filename),'startup','itemList.txt'); + let _mem = '{"items": ['; + for (let each in _table) + {(function(_idx, _arr){if(_idx>0){_mem += ', ';} _mem += JSON.stringify(_arr[_idx]);})(each, _table);} + _mem += ']}'; + console.log('_mem: ', _mem); + fs.writeFileSync(newFile, _mem, options); +}, /** * update an empty order with 4 items. update the amount field based on the sum of the line items * @param {addItems} _inbound - Order created with factory.newResource(NS, 'Order',.orderNumber) @@ -207,7 +242,7 @@ addOrder: function (_con, _order, _registry, _createNew, _bnc) _arr[_idx].extendedPrice = _item.unitPrice*_arr[_idx].quantity; _amount += _arr[_idx].extendedPrice; _items.push(JSON.stringify(_arr[_idx])); - })(each, _inbound.items)} + })(each, _inbound.items);} return ({'items': _items, 'amount': _amount}); }, /** @@ -215,22 +250,23 @@ addOrder: function (_con, _order, _registry, _createNew, _bnc) * was not initially working. This function is no longer in use. * @param {Order} _order - the inbound Order item retrieved from a registry * @return JSON object order elements + * @return {Order} JSON object order elements * @function */ - getOrderData: function (_order) - { - let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', - 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; - var _obj = {}; - for (let each in orderElements){(function(_idx, _arr) - { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements)} - _obj.buyer = _order.buyer.$identifier; - _obj.seller = _order.seller.$identifier; - _obj.provider = _order.seller.$provider; - _obj.shipper = _order.seller.$shipper; - _obj.financeCo = _order.seller.$financeCo; - return (_obj); - }, +getOrderData: function (_order) +{ + let orderElements = ['items', 'status', 'amount', 'created', 'cancelled', 'bought', 'ordered', 'dateBackordered', 'requestShipment', 'delivered', 'delivering', 'approved', + 'disputeOpened', 'disputeResolved', 'paymentRequested', 'orderRefunded', 'paid', 'dispute', 'resolve', 'backorder', 'refund']; + let _obj = {}; + for (let each in orderElements){(function(_idx, _arr) + { _obj[_arr[_idx]] = _order[_arr[_idx]]; })(each, orderElements);} + _obj.buyer = _order.buyer.$identifier; + _obj.seller = _order.seller.$identifier; + _obj.provider = _order.seller.$provider; + _obj.shipper = _order.seller.$shipper; + _obj.financeCo = _order.seller.$financeCo; + return (_obj); +}, /** * JSON object of available order status types and codes. This is used by nodejs @@ -254,128 +290,15 @@ addOrder: function (_con, _order, _registry, _createNew, _bnc) Refunded: {code: 13, text: 'Order Refunded'} }, /** - * the user experience is enhanced if the browser can be notified of aysnchronous events. - * the createMessateSockt function creates a web socket service to which the browser can - * attach. - * @param {integer} _port - port number to use for this socket connection - * @returns {websocket} - web socket connection to be used on the server side. + * New code to support sending messages to socket clients + * @param {Object} _locals - shared variables and functions from index.js + * @param {String} type - type of event message to put on channel + * @param {Event} event - event message */ - m_connection: null, - m_socketAddr: null, - m_socket: null, - createMessageSocket: function (_port) - { - var port = (typeof(_port) == 'undefined' || _port == null) ? app.get('port')+1 : _port - if (this.m_socket == null) - { - this.m_socketAddr = port; - this.m_socket= new ws.server({httpServer: http.createServer().listen(this.m_socketAddr)}); - var _this = this; - this.m_socket.on('request', function(request) - { - _this.m_connection = request.accept(null, request.origin); - _this.m_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.m_connection.sendUTF('connected'); - _this.m_connection.on('close', function(m_connection) {console.log('m_connection closed'); }); - }); - }); - } - return {conn: this.m_connection, socket: this.m_socketAddr}; - }, -/** - * the cs_connection is used to display blockchain information to the web browser over - * a sepaarate port from the user experience socket. - * @returns {websocket} - web socket connection to be used on the server side. - */ - - cs_connection: null, - cs_socketAddr: null, - cs_socket: null, - createChainSocket: function () - { - var port = app.get('port')+2; - if (this.cs_socket == null) - { - this.cs_socketAddr = port; - this.cs_socket= new ws.server({httpServer: http.createServer().listen(this.cs_socketAddr)}); - var _this = this; - this.cs_socket.on('request', function(request) - { - _this.cs_connection = request.accept(null, request.origin); - _this.cs_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.cs_connection.sendUTF('connected'); - _this.cs_connection.on('close', function(cs_connection) {console.log('cs_connection closed'); }); - }); - }); - } - return {conn: this.cs_connection, socket: this.cs_socketAddr}; - }, -/** - * the al_connection is used to display alerts to the unified view - * a sepaarate port from the user experience socket. - * @returns {websocket} - web socket connection to be used on the server side. - */ - -al_connection: null, -al_socketAddr: null, -al_socket: null, -createAlertSocket: function () +send: function (_locals, type, event) { - var port = app.get('port')+3; - if (this.al_socket == null) - { - this.al_socketAddr = port; - this.al_socket= new ws.server({httpServer: http.createServer().listen(this.al_socketAddr)}); - var _this = this; - this.al_socket.on('request', function(request) - { - _this.al_connection = request.accept(null, request.origin); - _this.al_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.al_connection.sendUTF(JSON.stringify({'type': 'connected', 'ID': 'admin', 'orderID': 'nought'})); - _this.al_connection.on('close', function(al_connection) {console.log('al_connection closed'); }); - }); - }); - } - return {conn: this.al_connection, socket: this.al_socketAddr}; -}, - -/** - * the cs_connection is used to display blockchain information to the web browser over - * a sepaarate port from the user experience socket. - * @returns {websocket} - web socket connection to be used on the server side. - */ - -f_connection: null, -f_socketAddr: null, -f_socket: null, -createFinanceAlertSocket: function () -{ - var port = app.get('port')+4; - if (this.f_socket == null) - { - this.f_socketAddr = port; - this.f_socket= new ws.server({httpServer: http.createServer().listen(this.f_socketAddr)}); - var _this = this; - this.f_socket.on('request', function(request) - { - _this.f_connection = request.accept(null, request.origin); - _this.f_connection.on('message', function(message) - { - console.log(message.utf8Data); - _this.f_connection.sendUTF(JSON.stringify({'type': 'connected', 'ID': 'admin', 'orderID': 'nought'})); - _this.f_connection.on('close', function(f_connection) {console.log('f_connection closed'); }); - }); - }); - } - return {conn: this.f_connection, socket: this.f_socketAddr}; -} - + _locals.processMessages({'type': type, 'data': event} ); } +}; module.exports = Z2Blockchain; \ No newline at end of file diff --git a/Chapter12/controller/restapi/features/composer/autoLoad.js b/Chapter12/controller/restapi/features/composer/autoLoad.js index 69dab55..da256aa 100644 --- a/Chapter12/controller/restapi/features/composer/autoLoad.js +++ b/Chapter12/controller/restapi/features/composer/autoLoad.js @@ -34,62 +34,13 @@ const financeCoID = 'easymoney@easymoneyinc.com'; const svc = require('./Z2B_Services'); const config = require('../../../env.json'); + /** * itemTable and memberTable are used by the server to reduce load time requests * for member secrets and item information */ let itemTable = new Array(); let memberTable = new Array(); -let socketAddr; - - - - - -/** - * getPort is used to return the port number for socket interactions so that - * the browser can receive asynchronous notifications of work in process. - * This helps the user understand the current status of the auto load process. - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * - * @function - */ -exports.getPort = function(req, res, next) { - let _conn = svc.createMessageSocket(); - res.send({'port': _conn.socket}); -}; - -/** - * getAlertPort is used to return the port number for socket interactions so that - * the browser can receive asynchronous notifications of work in process. - * This helps the user understand the current status of the auto load process. - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * - * @function - */ -exports.getAlertPort = function(req, res, next) { - let _conn = svc.createAlertSocket(); - res.send({'port': _conn.socket}); -}; - -/** - * getFinanceAlertPort is used to return the port number for socket interactions so that - * the browser can receive asynchronous notifications of work in process. - * This helps the user understand the current status of the auto load process. - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * - * @function - */ -exports.getFinanceAlertPort = function(req, res, next) { - let _conn = svc.createFinanceAlertSocket(); - res.send({'port': _conn.socket}); -}; /** * autoLoad reads the memberList.json file from the Startup folder and adds members, @@ -108,9 +59,9 @@ exports.autoLoad = function(req, res, next) { // connect to the network let businessNetworkConnection; let factory; let participant; - svc.createMessageSocket(); - socketAddr = svc.m_socketAddr; - let adminConnection = new AdminConnection(); +// svc.createMessageSocket(); +// socketAddr = svc.m_socketAddr; +let adminConnection = new AdminConnection(); // connection prior to V0.15 // adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW) // connection in v0.15 @@ -140,7 +91,7 @@ exports.autoLoad = function(req, res, next) { return participantRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { participant = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); @@ -148,7 +99,7 @@ exports.autoLoad = function(req, res, next) { participantRegistry.add(participant) .then(() => { console.log('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); - svc.m_connection.sendUTF('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); + svc.send(req.app.locals, 'Message', '['+_idx+'] '+_arr[_idx].companyName+' successfully added'); }) .then(() => { // an identity is required before a member can take action in the network. @@ -174,7 +125,9 @@ exports.autoLoad = function(req, res, next) { config.connectionProfile.keyValStore = _home+config.connectionProfile.keyValStore; let tempCard = new hlc_idCard(_meta, config.connectionProfile); return adminConnection.importCard(result.userID, tempCard) - .then ((_res) => { if (_res) {console.log('card updated');} else {console.log('card imported');} }) + .then ((_res) => { + if (_res) {console.log('card updated');} else {console.log('card imported');} + }) .catch((error) => { console.error('adminConnection.importCard failed. ',error.message); }); @@ -202,7 +155,7 @@ exports.autoLoad = function(req, res, next) { return assetRegistry.get(_arr[_idx].id) .then((_res) => { console.log('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.m_connection.sendUTF('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { // first, an Order Object is created @@ -216,8 +169,8 @@ exports.autoLoad = function(req, res, next) { const createNew = factory.newTransaction(config.composer.NS, 'CreateOrder'); order.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); order.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); - order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummy'); - order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummy'); + order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummyProvider'); + order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummyShipper'); order.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); createNew.order = factory.newRelationship(config.composer.NS, 'Order', order.$identifier); @@ -229,7 +182,7 @@ exports.autoLoad = function(req, res, next) { .then(() => { // then a createOrder transaction is processed which uses the chaincode // establish the order with it's initial transaction state. - svc.loadTransaction(svc.m_connection, createNew, order.orderNumber, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, order.orderNumber, businessNetworkConnection); }) .catch((error) => { // in the development environment, because of how timing is set up, it is normal to @@ -237,8 +190,8 @@ exports.autoLoad = function(req, res, next) { // logical transaction error. if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log('AL: '+_arr[_idx].id+' retrying assetRegistry.add for: '+_arr[_idx].id); - svc.addOrder(svc.m_connection, order, assetRegistry, createNew, businessNetworkConnection); - } + svc.addOrder(req.app.locals, order, assetRegistry, createNew, businessNetworkConnection); + } else {console.log('error with assetRegistry.add', error.message);} }); }); @@ -250,7 +203,7 @@ exports.autoLoad = function(req, res, next) { .catch((error) => {console.log('error with business network Connect', error.message);}); }) .catch((error) => {console.log('error with adminConnect', error.message);}); - res.send({'port': socketAddr}); + res.send({'result': 'Success'}); }; /** diff --git a/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/connection.json b/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/connection.json new file mode 100644 index 0000000..84312ef --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/connection.json @@ -0,0 +1 @@ +{"name":"hlfv1","type":"hlfv1","orderers":[{"url":"grpc://localhost:7050"}],"ca":{"url":"http://localhost:7054","name":"ca.org1.example.com"},"peers":[{"requestURL":"grpc://localhost:7051","eventURL":"grpc://localhost:7053"}],"channel":"composerchannel","mspID":"Org1MSP","timeout":300} \ No newline at end of file diff --git a/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/credentials/certificate b/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/credentials/certificate new file mode 100644 index 0000000..3adfdfc --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/credentials/certificate @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICGjCCAcCgAwIBAgIRANuOnVN+yd/BGyoX7ioEklQwCgYIKoZIzj0EAwIwczEL +MAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG +cmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh +Lm9yZzEuZXhhbXBsZS5jb20wHhcNMTcwNjI2MTI0OTI2WhcNMjcwNjI0MTI0OTI2 +WjBbMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN +U2FuIEZyYW5jaXNjbzEfMB0GA1UEAwwWQWRtaW5Ab3JnMS5leGFtcGxlLmNvbTBZ +MBMGByqGSM49AgEGCCqGSM49AwEHA0IABGu8KxBQ1GkxSTMVoLv7NXiYKWj5t6Dh +WRTJBHnLkWV7lRUfYaKAKFadSii5M7Z7ZpwD8NS7IsMdPR6Z4EyGgwKjTTBLMA4G +A1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIBmrZau7BIB9 +rRLkwKmqpmSecIaOOr0CF6Mi2J5H4aauMAoGCCqGSM49BAMCA0gAMEUCIQC4sKQ6 +CEgqbTYe48az95W9/hnZ+7DI5eSnWUwV9vCd/gIgS5K6omNJydoFoEpaEIwM97uS +XVMHPa0iyC497vdNURA= +-----END CERTIFICATE----- diff --git a/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/credentials/privateKey b/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/credentials/privateKey new file mode 100644 index 0000000..11b9fd4 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/credentials/privateKey @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg00IwLLBKoi/9ikb6 +ZOAV0S1XeNGWllvlFDeczRKQn2uhRANCAARrvCsQUNRpMUkzFaC7+zV4mClo+beg +4VkUyQR5y5Fle5UVH2GigChWnUoouTO2e2acA/DUuyLDHT0emeBMhoMC +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/metadata.json b/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/metadata.json new file mode 100644 index 0000000..ab54dce --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/cards/PeerAdmin@hlfv1/metadata.json @@ -0,0 +1 @@ +{"version":1,"userName":"PeerAdmin","roles":["PeerAdmin","ChannelAdmin"]} \ No newline at end of file diff --git a/Chapter12/controller/restapi/features/composer/creds/cards/admin@zerotoblockchain-network/connection.json b/Chapter12/controller/restapi/features/composer/creds/cards/admin@zerotoblockchain-network/connection.json new file mode 100644 index 0000000..84312ef --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/cards/admin@zerotoblockchain-network/connection.json @@ -0,0 +1 @@ +{"name":"hlfv1","type":"hlfv1","orderers":[{"url":"grpc://localhost:7050"}],"ca":{"url":"http://localhost:7054","name":"ca.org1.example.com"},"peers":[{"requestURL":"grpc://localhost:7051","eventURL":"grpc://localhost:7053"}],"channel":"composerchannel","mspID":"Org1MSP","timeout":300} \ No newline at end of file diff --git a/Chapter12/controller/restapi/features/composer/creds/cards/admin@zerotoblockchain-network/metadata.json b/Chapter12/controller/restapi/features/composer/creds/cards/admin@zerotoblockchain-network/metadata.json new file mode 100644 index 0000000..7f0fa95 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/cards/admin@zerotoblockchain-network/metadata.json @@ -0,0 +1 @@ +{"version":1,"userName":"admin","businessNetwork":"zerotoblockchain-network","enrollmentSecret":"adminpw"} \ No newline at end of file diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457-priv b/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457-priv new file mode 100644 index 0000000..11b9fd4 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457-priv @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg00IwLLBKoi/9ikb6 +ZOAV0S1XeNGWllvlFDeczRKQn2uhRANCAARrvCsQUNRpMUkzFaC7+zV4mClo+beg +4VkUyQR5y5Fle5UVH2GigChWnUoouTO2e2acA/DUuyLDHT0emeBMhoMC +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457-pub b/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457-pub new file mode 100644 index 0000000..8c2855f --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457-pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEa7wrEFDUaTFJMxWgu/s1eJgpaPm3 +oOFZFMkEecuRZXuVFR9hooAoVp1KKLkztntmnAPw1Lsiwx09HpngTIaDAg== +-----END PUBLIC KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/PeerAdmin b/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/PeerAdmin new file mode 100644 index 0000000..7db3ed0 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/PeerAdmin@hlfv1/PeerAdmin @@ -0,0 +1 @@ +{"name":"PeerAdmin","mspid":"Org1MSP","roles":null,"affiliation":"","enrollmentSecret":"","enrollment":{"signingIdentity":"114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457","identity":{"certificate":"-----BEGIN CERTIFICATE-----\nMIICGjCCAcCgAwIBAgIRANuOnVN+yd/BGyoX7ioEklQwCgYIKoZIzj0EAwIwczEL\nMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG\ncmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMTcwNjI2MTI0OTI2WhcNMjcwNjI0MTI0OTI2\nWjBbMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN\nU2FuIEZyYW5jaXNjbzEfMB0GA1UEAwwWQWRtaW5Ab3JnMS5leGFtcGxlLmNvbTBZ\nMBMGByqGSM49AgEGCCqGSM49AwEHA0IABGu8KxBQ1GkxSTMVoLv7NXiYKWj5t6Dh\nWRTJBHnLkWV7lRUfYaKAKFadSii5M7Z7ZpwD8NS7IsMdPR6Z4EyGgwKjTTBLMA4G\nA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIBmrZau7BIB9\nrRLkwKmqpmSecIaOOr0CF6Mi2J5H4aauMAoGCCqGSM49BAMCA0gAMEUCIQC4sKQ6\nCEgqbTYe48az95W9/hnZ+7DI5eSnWUwV9vCd/gIgS5K6omNJydoFoEpaEIwM97uS\nXVMHPa0iyC497vdNURA=\n-----END CERTIFICATE-----\n"}}} \ No newline at end of file diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/157ef0c5933c7d5261153162b6b19b96554687e00c2c9daf45db7811a0c74b84-priv b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/157ef0c5933c7d5261153162b6b19b96554687e00c2c9daf45db7811a0c74b84-priv new file mode 100644 index 0000000..75b209b --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/157ef0c5933c7d5261153162b6b19b96554687e00c2c9daf45db7811a0c74b84-priv @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgnGx1N7LcnQd9zZRo +NW7jlt7fB92neFClgWXfQwjGEJOhRANCAARH66vzjgmgc9yCygbYUWyG1CBVyYBL +EksdAjal58R21Bs1vERnNUS4qZgl1FtZfQTic+uBrz2lrpWiiTcIHglF +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/157ef0c5933c7d5261153162b6b19b96554687e00c2c9daf45db7811a0c74b84-pub b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/157ef0c5933c7d5261153162b6b19b96554687e00c2c9daf45db7811a0c74b84-pub new file mode 100644 index 0000000..55dd524 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/157ef0c5933c7d5261153162b6b19b96554687e00c2c9daf45db7811a0c74b84-pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAER+ur844JoHPcgsoG2FFshtQgVcmA +SxJLHQI2pefEdtQbNbxEZzVEuKmYJdRbWX0E4nPrga89pa6Vook3CB4JRQ== +-----END PUBLIC KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/210a472603fb250e838c0e68affc6f04260b40ac8871f96fcf1789e8ae033e89-priv b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/210a472603fb250e838c0e68affc6f04260b40ac8871f96fcf1789e8ae033e89-priv new file mode 100644 index 0000000..e464a16 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/210a472603fb250e838c0e68affc6f04260b40ac8871f96fcf1789e8ae033e89-priv @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg3WweHXn9YueI21bv +1NJDoOr6sfkoF+N+i7c1HrG7d2ShRANCAARWXvrkECSC0Pyq5TUhXR0O+DwzI/E6 +G8dSpw/BsBQGY64IvGtjQT3Q83IaltXi6FuDO8X5a5v/A61xQxxi4wb7 +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/210a472603fb250e838c0e68affc6f04260b40ac8871f96fcf1789e8ae033e89-pub b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/210a472603fb250e838c0e68affc6f04260b40ac8871f96fcf1789e8ae033e89-pub new file mode 100644 index 0000000..c493b18 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/210a472603fb250e838c0e68affc6f04260b40ac8871f96fcf1789e8ae033e89-pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEVl765BAkgtD8quU1IV0dDvg8MyPx +OhvHUqcPwbAUBmOuCLxrY0E90PNyGpbV4uhbgzvF+Wub/wOtcUMcYuMG+w== +-----END PUBLIC KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/3c64462a8b1f951653463df88192c74f8388e18971793d32f21df75b6eb33e19-priv b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/3c64462a8b1f951653463df88192c74f8388e18971793d32f21df75b6eb33e19-priv new file mode 100644 index 0000000..a07d791 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/3c64462a8b1f951653463df88192c74f8388e18971793d32f21df75b6eb33e19-priv @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgWSEa4+KRO7Egdbfv +fedhir19rU5jlZPmdl/sIxiBNVihRANCAATFZWF2fAgOsghZoGfcdqV46RNTQB5D +iZAWh9Xk130ajzpKvSFK8HtQVqk+Idq4TLNpYdLM/VC+ookamG1z4A5w +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/3c64462a8b1f951653463df88192c74f8388e18971793d32f21df75b6eb33e19-pub b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/3c64462a8b1f951653463df88192c74f8388e18971793d32f21df75b6eb33e19-pub new file mode 100644 index 0000000..fe55035 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/3c64462a8b1f951653463df88192c74f8388e18971793d32f21df75b6eb33e19-pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAExWVhdnwIDrIIWaBn3HaleOkTU0Ae +Q4mQFofV5Nd9Go86Sr0hSvB7UFapPiHauEyzaWHSzP1QvqKJGphtc+AOcA== +-----END PUBLIC KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/6926053f3f7fa76f2b51f5d602afe850d9cabb18ffd763c73d5205df5a3f9bfb-priv b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/6926053f3f7fa76f2b51f5d602afe850d9cabb18ffd763c73d5205df5a3f9bfb-priv new file mode 100644 index 0000000..dbc6dbc --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/6926053f3f7fa76f2b51f5d602afe850d9cabb18ffd763c73d5205df5a3f9bfb-priv @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgjnwJZpAOpr7hevOi +8OpJ9xrPBT34vHexhMxrofbDrfGhRANCAASxoTdi/H9lYTymkRisb8B5Qch7iLVL +IRZ37Vx2wIm+8xQ8SjTIGMda1K39XGgGU39ZJ4z2I4lxD9GYbMtClA8Y +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/6926053f3f7fa76f2b51f5d602afe850d9cabb18ffd763c73d5205df5a3f9bfb-pub b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/6926053f3f7fa76f2b51f5d602afe850d9cabb18ffd763c73d5205df5a3f9bfb-pub new file mode 100644 index 0000000..4714733 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/6926053f3f7fa76f2b51f5d602afe850d9cabb18ffd763c73d5205df5a3f9bfb-pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEsaE3Yvx/ZWE8ppEYrG/AeUHIe4i1 +SyEWd+1cdsCJvvMUPEo0yBjHWtSt/VxoBlN/WSeM9iOJcQ/RmGzLQpQPGA== +-----END PUBLIC KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/978c7f2e9314c72cb0c564883dced69bfdffe8457cbd790a3d6f289d56bc0220-priv b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/978c7f2e9314c72cb0c564883dced69bfdffe8457cbd790a3d6f289d56bc0220-priv new file mode 100644 index 0000000..db32c87 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/978c7f2e9314c72cb0c564883dced69bfdffe8457cbd790a3d6f289d56bc0220-priv @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgAJhQXYndLtBRv7Sc +NGG7T19NszqmiPbGVdPlfkNnbZehRANCAASjJYD3s/yyq6aWHZKCrXrTJ1307DlZ +VZNpLMSqpAnjMaloMH5Ed0Ch1xBAxTDrMFzz0mYB0YYKckl0Sb3NCc7V +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/978c7f2e9314c72cb0c564883dced69bfdffe8457cbd790a3d6f289d56bc0220-pub b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/978c7f2e9314c72cb0c564883dced69bfdffe8457cbd790a3d6f289d56bc0220-pub new file mode 100644 index 0000000..c2b4a1d --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/978c7f2e9314c72cb0c564883dced69bfdffe8457cbd790a3d6f289d56bc0220-pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoyWA97P8squmlh2Sgq160ydd9Ow5 +WVWTaSzEqqQJ4zGpaDB+RHdAodcQQMUw6zBc89JmAdGGCnJJdEm9zQnO1Q== +-----END PUBLIC KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/9b1be46b5ce3ce11a301282751df96a801f7e0c3601f040f12a0915519cbda16-priv b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/9b1be46b5ce3ce11a301282751df96a801f7e0c3601f040f12a0915519cbda16-priv new file mode 100644 index 0000000..aa29eb9 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/9b1be46b5ce3ce11a301282751df96a801f7e0c3601f040f12a0915519cbda16-priv @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgVknENe69G9Bpzw9V +1LRObfxQRUg3T2+NS70AcgZT3Z2hRANCAASwvvcU9VBWcV37xluwmHfvvB5w97TA +S2YD0mD+8WNTJ11V+t6oCD3cvkgePDwlouZyVAvcy1p+4wHPLyfio7Nq +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/9b1be46b5ce3ce11a301282751df96a801f7e0c3601f040f12a0915519cbda16-pub b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/9b1be46b5ce3ce11a301282751df96a801f7e0c3601f040f12a0915519cbda16-pub new file mode 100644 index 0000000..819c22f --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/9b1be46b5ce3ce11a301282751df96a801f7e0c3601f040f12a0915519cbda16-pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEsL73FPVQVnFd+8ZbsJh377wecPe0 +wEtmA9Jg/vFjUyddVfreqAg93L5IHjw8JaLmclQL3MtafuMBzy8n4qOzag== +-----END PUBLIC KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/admin b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/admin new file mode 100644 index 0000000..9be6ecf --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/admin @@ -0,0 +1 @@ +{"name":"admin","mspid":"Org1MSP","roles":null,"affiliation":"","enrollmentSecret":"","enrollment":{"signingIdentity":"210a472603fb250e838c0e68affc6f04260b40ac8871f96fcf1789e8ae033e89","identity":{"certificate":"-----BEGIN CERTIFICATE-----\nMIIB8DCCAZegAwIBAgIUPy38KPB78U7H+M4iWBqefDs0DKEwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTgwOTA0MTQxNTAwWhcNMTkwOTA0MTQx\nNTAwWjAQMQ4wDAYDVQQDEwVhZG1pbjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA\nBFZe+uQQJILQ/KrlNSFdHQ74PDMj8Tobx1KnD8GwFAZjrgi8a2NBPdDzchqW1eLo\nW4M7xflrm/8DrXFDHGLjBvujbDBqMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8E\nAjAAMB0GA1UdDgQWBBScgfVr0UcRWjGWUIrqGNBVOr/2pDArBgNVHSMEJDAigCAZ\nq2WruwSAfa0S5MCpqqZknnCGjjq9AhejItieR+GmrjAKBggqhkjOPQQDAgNHADBE\nAiB9Zl01J8cWlx2veHMt2vELYeBc2X9oX4t7vkaVK8zdCwIgF86+wM16VUvcgkBk\nUeRsni/BXFdPW1AwXDdcHqmbANg=\n-----END CERTIFICATE-----\n"}}} \ No newline at end of file diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/e0bf1c87fb12b9a7c67fc3f571368cea034e3166974615868c02140aeaa7fc54-priv b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/e0bf1c87fb12b9a7c67fc3f571368cea034e3166974615868c02140aeaa7fc54-priv new file mode 100644 index 0000000..ab87b87 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/e0bf1c87fb12b9a7c67fc3f571368cea034e3166974615868c02140aeaa7fc54-priv @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgVBfyT/v+XQ+4B2Ql ++6hDZFXUrtpviB+yLY3OBj6WS5qhRANCAAQ9PBILCLDwf9sJPIO6wLvplW1PgwMU +mfrovrdcc7ReuZ8LCDM9BuCoWfh48stLh1Bh0PVfm3ZppVuLl090Ifmj +-----END PRIVATE KEY----- diff --git a/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/e0bf1c87fb12b9a7c67fc3f571368cea034e3166974615868c02140aeaa7fc54-pub b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/e0bf1c87fb12b9a7c67fc3f571368cea034e3166974615868c02140aeaa7fc54-pub new file mode 100644 index 0000000..8a489f6 --- /dev/null +++ b/Chapter12/controller/restapi/features/composer/creds/client-data/admin@zerotoblockchain-network/e0bf1c87fb12b9a7c67fc3f571368cea034e3166974615868c02140aeaa7fc54-pub @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEPTwSCwiw8H/bCTyDusC76ZVtT4MD +FJn66L63XHO0XrmfCwgzPQbgqFn4ePLLS4dQYdD1X5t2aaVbi5dPdCH5ow== +-----END PUBLIC KEY----- diff --git a/Chapter12/controller/restapi/features/composer/hlcAdmin.js b/Chapter12/controller/restapi/features/composer/hlcAdmin.js index 8e9e8b9..46b188c 100644 --- a/Chapter12/controller/restapi/features/composer/hlcAdmin.js +++ b/Chapter12/controller/restapi/features/composer/hlcAdmin.js @@ -24,8 +24,7 @@ const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefi const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; -// const svc = require('./Z2B_Services'); -// const mod = 'hlcAdmin.js'; + /** * display the admin and network info diff --git a/Chapter12/controller/restapi/features/composer/hlcClient.js b/Chapter12/controller/restapi/features/composer/hlcClient.js index 7fb32ee..fc7955c 100644 --- a/Chapter12/controller/restapi/features/composer/hlcClient.js +++ b/Chapter12/controller/restapi/features/composer/hlcClient.js @@ -245,7 +245,7 @@ exports.orderAction = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(' retrying assetRegistry.update for: '+req.body.orderNo); - svc.loadTransaction(svc.m_connection, updateOrder, req.body.orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, updateOrder, req.body.orderNo, businessNetworkConnection); } else {console.log(req.body.orderNo+' submitTransaction to update status to '+req.body.action+' failed with text: ',error.message);} @@ -330,7 +330,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else {console.log(orderNo+' submitTransaction failed with text: ',error.message);} @@ -339,7 +339,7 @@ exports.addOrder = function (req, res, next) { .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(orderNo+' retrying assetRegistry.add for: '+orderNo); - svc.loadTransaction(createNew, orderNo, businessNetworkConnection); + svc.loadTransaction(req.app.locals, createNew, orderNo, businessNetworkConnection); } else { @@ -354,46 +354,11 @@ exports.addOrder = function (req, res, next) { }); }) .catch((error) => { - console.log(orderNo+' business network connection failed: text',error.message); + console.log(method + ' : '+orderNo+' business network connection failed: text',error.message); res.send({'result': 'failed', 'error':' order '+orderNo+' add failed on on business network connection '+error.message}); }); }; -/** - * Register for all of the available Z2BEvents - * @param {express.req} req - the inbound request object from the client - * @param {express.res} res - the outbound response object for communicating back to client - * @param {express.next} next - an express service to enable post processing prior to responding to the client - * @returns {Object} - returns are via res.send -*/ -exports.init_z2bEvents = function (req, res, next) -{ - let method = 'init_z2bEvents'; - if (bRegistered) {res.send('Already Registered');} - else{ - bRegistered = true; - let _conn = svc.createAlertSocket(); - let businessNetworkConnection; - businessNetworkConnection = new BusinessNetworkConnection(); - businessNetworkConnection.setMaxListeners(50); - // - // v0.14 - // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) - // - // v0.15 - return businessNetworkConnection.connect(config.composer.adminCard) - .then(() => { - // using the businessNetworkConnection, start monitoring for events. - // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information - // ========> Your Code Goes Here <========= - res.send('event registration complete'); - }).catch((error) => { - // if an error is encountered, log the error and send it back to the requestor - // ========> Your Code Goes Here <========= - res.send(method+' business network connection failed'+error.message); - }); - } -}; /** * _monitor * @param {WebSocket} _conn - web socket to use for member event posting @@ -401,7 +366,7 @@ exports.init_z2bEvents = function (req, res, next) * @param {Event} _event - the event just emitted * */ -function _monitor(_conn, _f_conn, _event) +function _monitor(locals, _event) { let method = '_monitor'; console.log(method+ ' _event received: '+_event.$type+' for Order: '+_event.orderID); @@ -446,4 +411,40 @@ function _monitor(_conn, _f_conn, _event) break; } -} \ No newline at end of file +} + +/** + * Register for all of the available Z2BEvents + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + * @returns {Object} - returns are via res.send +*/ +exports.init_z2bEvents = function (req, res, next) +{ + let method = 'init_z2bEvents'; + if (bRegistered) {res.send('Already Registered');} + else{ + bRegistered = true; +// svc.createAlertSocket(); + let businessNetworkConnection; + businessNetworkConnection = new BusinessNetworkConnection(); + businessNetworkConnection.setMaxListeners(50); + // + // v0.14 + // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // + // v0.15 + return businessNetworkConnection.connect(config.composer.adminCard) + .then(() => { + // using the businessNetworkConnection, start monitoring for events. + // when an event is provided, call the _monitor function, passing in the al_connection, f_connection and event information + businessNetworkConnection.on('event', (event) => {_monitor(req.app.locals, event); }); + res.send('event registration complete'); + }).catch((error) => { + // if an error is encountered, log the error and send it back to the requestor + console.log(method+' business network connection failed'+error.message); + res.send(method+' business network connection failed'+error.message); + }); + } +}; diff --git a/Chapter12/controller/restapi/features/composer/queryBlockChain.js b/Chapter12/controller/restapi/features/composer/queryBlockChain.js index 9b6a396..75b67d3 100644 --- a/Chapter12/controller/restapi/features/composer/queryBlockChain.js +++ b/Chapter12/controller/restapi/features/composer/queryBlockChain.js @@ -12,8 +12,9 @@ * limitations under the License. */ -var path = require('path'); -var fs = require('fs'); +'use strict'; +let path = require('path'); +let fs = require('fs'); const express = require('express'); const app = express(); const cfenv = require('cfenv'); @@ -24,10 +25,10 @@ const hfc = require('fabric-client'); const hfcEH = require('fabric-client/lib/EventHub'); const svc = require('./Z2B_Services'); -const util = require('./Z2B_Utilities'); -const financeCoID = 'easymoney@easymoneyinc.com'; +// const util = require('./Z2B_Utilities'); +// const financeCoID = 'easymoney@easymoneyinc.com'; const config = require('../../../env.json'); -var chainEvents = false; +let chainEvents = false; @@ -38,11 +39,13 @@ var chainEvents = false; * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainInfo = function(req, res, next) { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); - console.log(wallet_path); +exports.getChainInfo = function(req, res, next) +{ + let method='getChainInfo'; + let HOST_NAME = req.headers.host; + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); Promise.resolve().then(() => { // // As of 9/28/2017 there is a known and unresolved bug in HyperLedger Fabric @@ -61,29 +64,43 @@ exports.getChainInfo = function(req, res, next) { // change PeerAdmin in following line to adminID return client.getUserContext(config.composer.PeerAdmin, true);}) .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + if (user === null || user === undefined || user.isEnrolled() === false) + { console.error('User not defined, or not enrolled - error');} + if (HOST_NAME.slice(0,9) === 'localhost') + { + console.log(method+" running locally"); channel = client.newChannel(config.fabric.channelName); channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - }) + }else + { + console.log(method+" running remotely, not supported in Chapter 12"); + } + }) .then(() => { return channel.queryInfo() .then((blockchainInfo) => { if (blockchainInfo) { - res.send({"result": "success", "currentHash": blockchainInfo.currentBlockHash.toString("hex"), blockchain: blockchainInfo}); + res.send({'result': 'success', 'currentHash': blockchainInfo.currentBlockHash.toString('hex'), blockchain: blockchainInfo}); } else { console.log('response_payload is null'); - res.send({"result": "uncertain", "message": 'response_payload is null'}); + res.send({'result': 'uncertain', 'message': 'response_payload is null'}); } }) .catch((_err) => { - console.log("queryInfo failed with _err = ", _err); - res.send({"result": "failed", "message": _err.message}); - }); + console.log('queryInfo failed with _err = ', _err); + res.send({'result': 'failed', 'message': _err.message}); + }); }); - }); -} + }); +}; /** * get chain events @@ -92,37 +109,55 @@ exports.getChainInfo = function(req, res, next) { * @param {express.next} next - an express service to enable post processing prior to responding to the client * @function */ -exports.getChainEvents = function(req, res, next) { +exports.getChainEvents = function(req, res, next) +{ + let method = 'getChainEvents'; + let HOST_NAME = req.headers.host; if (chainEvents) {res.send({'port': svc.cs_socketAddr});} else { - var channel = {}; - var client = null; - var wallet_path = path.join(__dirname, 'creds'); + let channel = {}; + let client = null; + let wallet_path = path.join(__dirname, 'creds'); + Promise.resolve().then(() => { client = new hfc(); return hfc.newDefaultKeyValueStore({ path: wallet_path }) .then((wallet) => { client.setStateStore(wallet); // change PeerAdmin in following line to adminID - return client.getUserContext(config.composer.PeerAdmin, true);}) - .then((user) => { - if (user === null || user === undefined || user.isEnrolled() === false) - {console.error("User not defined, or not enrolled - error");} - channel = client.newChannel(config.fabric.channelName); - channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); - channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); - // change Admin in following line to admin - var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); - var adminPEM = fs.readFileSync(pemPath).toString(); - var bcEvents = new hfcEH(client); - bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + return client.getUserContext(config.composer.PeerAdmin, true); + }) + .then((user) => { + if (user === null || user === undefined || user.isEnrolled() === false) + {console.error(method+': User not defined, or not enrolled - error');} + // This routine as written will only work with the kubernetes deployed blockchain. It will not work with the docker image. + // adding a check for localhost only tells you that the nodejs portion is running on your local system. This does not + // also tell you that the blockchain is/is not running in your local docker environment. + // To support switching between local docker and remote kubernetes on cluster, an extra config element would be required. + // The logical place for this is in the env.json file. If you do that, then the code in this routine will need to be updated so that each + // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. + // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial + // get the channel name + channel = client.newChannel(config.fabric.channelName); + //get the request URL for the Peer0 container + channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); + // get the orderer URL + channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); + // change Admin in following line to admin + var pemPath = path.join(__dirname,'creds','admin@org.hyperledger.composer.system-cert.pem'); + var adminPEM = fs.readFileSync(pemPath).toString(); + var bcEvents = new hfcEH(client); + bcEvents.setPeerAddr(config.fabric.peerEventURL, {pem: adminPEM}); + bcEvents.registerBlockEvent( + function(event){svc.send(req.app.locals, 'BlockChain', event);}, + function(error){console.log(method+': registerBlockEvent error: ', error);} + ); bcEvents.connect(); - svc.createChainSocket(); - bcEvents.registerBlockEvent(function(event) {svc.cs_connection.sendUTF(JSON.stringify(event));}); - chainEvents = true; - res.send({'port': svc.cs_socketAddr}); - }) - }); - } -} + chainEvents = true; + res.send({'port': svc.cs_socketAddr}); + }) + .catch((err) => { console.log(method+': getUserContext failed: ',err);}); + }); + } +}; diff --git a/Chapter12/controller/restapi/router.js b/Chapter12/controller/restapi/router.js index ba7b3cc..14883e7 100644 --- a/Chapter12/controller/restapi/router.js +++ b/Chapter12/controller/restapi/router.js @@ -32,12 +32,8 @@ router.get('/fabric/getChainEvents', hlcFabric.getChainEvents); router.get('/fabric/getHistory', hlcAdmin.getHistory); router.post('/setup/autoLoad*', setup.autoLoad); -router.get('/setup/getPort*', setup.getPort); router.get('/composer/client/initEventRegistry*', hlcClient.init_z2bEvents); -router.get('/setup/getAlertPort*', setup.getAlertPort); -router.get('/setup/getFinanceAlertPort*', setup.getFinanceAlertPort); - module.exports = router; let count = 0; /** @@ -77,6 +73,7 @@ router.get('/composer/admin/getAllProfiles*', hlcAdmin.getAllProfiles); router.get('/composer/admin/listAsAdmin*', hlcAdmin.listAsAdmin); router.get('/composer/admin/getRegistries*', hlcAdmin.getRegistries); + router.post('/composer/admin/createProfile*', hlcAdmin.createProfile); router.post('/composer/admin/deleteProfile*', hlcAdmin.deleteProfile); router.post('/composer/admin/deploy*', hlcAdmin.deploy); @@ -96,6 +93,7 @@ router.post('/composer/admin/checkCard*', hlcAdmin.checkCard); router.post('/composer/admin/createCard*', hlcAdmin.createCard); router.post('/composer/admin/issueIdentity*', hlcAdmin.issueIdentity); + // router requests specific to the Buyer router.get('/composer/client/getItemTable*', hlcClient.getItemTable); router.post('/composer/client/getMyOrders*', hlcClient.getMyOrders); diff --git a/Chapter12/favicon.ico b/Chapter12/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter12/favicon.ico and /dev/null differ diff --git a/Chapter12/index.js b/Chapter12/index.js index 70319d6..cf79cb7 100644 --- a/Chapter12/index.js +++ b/Chapter12/index.js @@ -14,25 +14,28 @@ /* * Zero to Blockchain */ -var express = require('express'); -var http = require('http'); -var https = require('https'); -var path = require('path'); -var fs = require('fs'); -var mime = require('mime'); -var bodyParser = require('body-parser'); -var cfenv = require('cfenv'); -var cookieParser = require('cookie-parser'); -var session = require('express-session'); +'use strict'; +const express = require('express'); +const http = require('http'); +const ws = require('websocket').server; +// const https = require('https'); +const path = require('path'); +const fs = require('fs'); +const mime = require('mime'); +const bodyParser = require('body-parser'); +const cfenv = require('cfenv'); -var vcapServices = require('vcap_services'); -var uuid = require('uuid'); -var env = require('./controller/envV2.json'); -var sessionSecret = env.sessionSecret; -var appEnv = cfenv.getAppEnv(); -var app = express(); -var busboy = require('connect-busboy'); +const cookieParser = require('cookie-parser'); +// const session = require('express-session'); + +// const vcapServices = require('vcap_services'); +// const uuid = require('uuid'); +const env = require('./controller/envV2.json'); +const sessionSecret = env.sessionSecret; +const appEnv = cfenv.getAppEnv(); +const app = express(); +const busboy = require('connect-busboy'); app.use(busboy()); // the session secret is a text string of arbitrary length which is @@ -49,7 +52,8 @@ app.use(cookieParser(sessionSecret)); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); -app.set('appName', 'z2b-chapter07'); +app.set('appName', 'z2b-chapter12'); +process.title = 'Z2B-C12'; app.set('port', appEnv.port); app.set('views', path.join(__dirname + '/HTML')); @@ -59,14 +63,58 @@ app.use(express.static(__dirname + '/HTML')); app.use(bodyParser.json()); // Define your own router file in controller folder, export the router, add it into the index.js. -// app.use('/', require("./controller/yourOwnRouter")); -app.use('/', require("./controller/restapi/router")); +app.use('/', require('./controller/restapi/router')); + +let server = http.createServer(); +let clients = []; +app.locals.index=-1; +/** + * WebSocket server + */ +app.locals.wsServer = new ws({httpServer: server}); +app.locals.wsServer.on('request', function(request) +{ + // create a connection back to the requestor + app.locals.connection = request.accept(null, request.origin); + // we need to know client index to remove them on 'close' event + app.locals.index = clients.push(app.locals.connection) - 1; + // save the newly created connection. This is so that we can support many connections to many browsers simultaneously + console.log((new Date()) + ' Connection accepted.'); + app.locals.connection.on('message', function(message) + { let obj ={ime: (new Date()).getTime(),text: message.utf8Data}; + // broadcast message to all connected clients + let json = JSON.stringify({ type:'Message', data: obj }); + app.locals.processMessages(json); + }); + + // user disconnected + app.locals.connection.on('close', function(_conn) { + console.log((new Date()) + ' Peer '+ app.locals.connection.socket._peername.address+':'+app.locals.connection.socket._peername.port+' disconnected with reason code: "'+_conn+'".'); + // remove user from the list of connected clients + // each browser connection has a unique address and socket combination + // When a browser session is disconnected, remove it from the array so we don't waste processing time sending messages to empty queues. + for (let each in clients) + {(function(_idx, _arr) + {if ((_arr[_idx].socket._peername.address === app.locals.connection.socket._peername.address) && (_arr[_idx].socket._peername.port === app.locals.connection.socket._peername.port)) + {clients.splice(_idx, 1);} + })(each, clients);} + }); +}); -if (cfenv.getAppEnv().isLocal == true) - { var server = app.listen(app.get('port'), function() {console.log('Listening locally on port %d', server.address().port);}); } - else - { var server = app.listen(app.get('port'), function() {console.log('Listening remotely on port %d', server.address().port);}); } +/** + * callable function to send messages over web socket + * @param {JSON} _jsonMsg - json formatted content to be sent as message data + */ +function processMessages (_jsonMsg) +{ + for (let i=0; i < clients.length; i++) {clients[i].send(JSON.stringify(_jsonMsg));} +} +// make the processMessages function available to all modules in this app. +app.locals.processMessages = processMessages; +// now set up the http server +server.on( 'request', app ); +server.listen(appEnv.port, function() {console.log('Listening locally on port %d', server.address().port);}); /** * load any file requested on the server * @param {express.req} req - the inbound request object from the client @@ -74,16 +122,16 @@ if (cfenv.getAppEnv().isLocal == true) * @function */ function loadSelectedFile(req, res) { - var uri = req.originalUrl; - var filename = __dirname + "/HTML" + uri; + let uri = req.originalUrl; + let filename = __dirname + '/HTML' + uri; fs.readFile(filename, function(err, data) { if (err) { console.log('Error loading ' + filename + ' error: ' + err); return res.status(500).send('Error loading ' + filename); } - var type = mime.lookup(filename); - res.setHeader('content-type', type); + let type = mime.lookup(filename); + res.setHeader('content-type', type); res.writeHead(200); res.end(data); }); diff --git a/Chapter12/network/lib/sample.js b/Chapter12/network/lib/sample.js index 4ce83b2..174b4db 100644 --- a/Chapter12/network/lib/sample.js +++ b/Chapter12/network/lib/sample.js @@ -126,7 +126,7 @@ function OrderFromSupplier(purchase) { * @transaction */ function RequestShipping(purchase) { - if (purchase.order.status == JSON.stringify(orderStatus.Ordered)) + if ((purchase.order.status == JSON.stringify(orderStatus.Ordered)) || (purchase.order.status == JSON.stringify(orderStatus.Backordered))) { purchase.order.shipper = purchase.shipper; purchase.order.requestShipment = new Date().toISOString(); @@ -196,7 +196,6 @@ function RequestPayment(purchase) { {purchase.order.status = JSON.stringify(orderStatus.PayRequest); purchase.order.financeCo = purchase.financeCo; purchase.order.paymentRequested = new Date().toISOString(); - } return getAssetRegistry('org.acme.Z2BTestNetwork.Order') .then(function (assetRegistry) { return assetRegistry.update(purchase.order) @@ -206,6 +205,7 @@ function RequestPayment(purchase) { return (_res); }).catch(function(error){return(error);}); }); + } } /** * Record a payment to the seller @@ -216,7 +216,6 @@ function AuthorizePayment(purchase) { if ((JSON.parse(purchase.order.status).text == orderStatus.PayRequest.text ) || (JSON.parse(purchase.order.status).text == orderStatus.Resolve.text )) {purchase.order.status = JSON.stringify(orderStatus.Authorize); purchase.order.approved = new Date().toISOString(); - } return getAssetRegistry('org.acme.Z2BTestNetwork.Order') .then(function (assetRegistry) { return assetRegistry.update(purchase.order) @@ -226,6 +225,7 @@ function AuthorizePayment(purchase) { return (_res); }).catch(function(error){return(error);}); }); + } } /** * Record a payment to the seller @@ -236,7 +236,6 @@ function Pay(purchase) { if (JSON.parse(purchase.order.status).text == orderStatus.Authorize.text ) {purchase.order.status = JSON.stringify(orderStatus.Paid); purchase.order.paid = new Date().toISOString(); - } return getAssetRegistry('org.acme.Z2BTestNetwork.Order') .then(function (assetRegistry) { return assetRegistry.update(purchase.order) @@ -246,6 +245,7 @@ function Pay(purchase) { return (_res); }).catch(function(error){return(error);}); }); + } } /** * Record a dispute by the buyer diff --git a/Chapter13/HTML/admin.html b/Chapter13/HTML/admin.html index 53b3a2d..1c0e9fe 100644 --- a/Chapter13/HTML/admin.html +++ b/Chapter13/HTML/admin.html @@ -1,6 +1,7 @@

    Why All The Changes?

    +

    NodeJS last restarted:

    diff --git a/Chapter13/HTML/favicon.ico b/Chapter13/HTML/favicon.ico old mode 100755 new mode 100644 index fc9e25d..3dbe425 Binary files a/Chapter13/HTML/favicon.ico and b/Chapter13/HTML/favicon.ico differ diff --git a/Chapter13/HTML/index.html b/Chapter13/HTML/index.html index 49183d2..0ac3bef 100644 --- a/Chapter13/HTML/index.html +++ b/Chapter13/HTML/index.html @@ -1,88 +1,90 @@ - - - - - - - - -
    - +
    + +
    +
    +
    +
    +

    +

    +

    NodeJS last restarted:

    + +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Chapter13/HTML/js/z2b-admin.js b/Chapter13/HTML/js/z2b-admin.js index f3c3ffc..21244f1 100644 --- a/Chapter13/HTML/js/z2b-admin.js +++ b/Chapter13/HTML/js/z2b-admin.js @@ -25,11 +25,13 @@ let _blctr = 0; */ function loadAdminUX () { + let methodName = 'loadAdminUX'; let toLoad = 'admin.html'; $.when($.get(toLoad)).done(function (page) {$('#body').empty(); $('#body').append(page); updatePage('admin'); + $.when($.get('/setup/getLastRestart')).done(function(_res) { $('#lastUpdate').append(_res.timeStamp); }); listMemRegistries(); }); } diff --git a/Chapter13/HTML/js/z2b-initiate.js b/Chapter13/HTML/js/z2b-initiate.js index e5b82d6..526e5e6 100644 --- a/Chapter13/HTML/js/z2b-initiate.js +++ b/Chapter13/HTML/js/z2b-initiate.js @@ -59,6 +59,8 @@ function initPage () console.log('looking for kubernetes at: '+_addr); // goMultiLingual() establishes what languages are available for this web app, populates the header with available languages and sets the default language to US_English goMultiLingual('US_English', 'index'); + // get the timestamp for when the network was last loaded + $.when($.get('/setup/getLastRestart')).done(function(_res) { $('#lastUpdate').append(_res.timeStamp); }) // singleUX loads the members already present in the network memberLoad(); // goChainEvents creates a web socket connection with the server and initiates blockchain event monitoring diff --git a/Chapter13/README.md b/Chapter13/README.md index ffa2eaa..78864c4 100644 --- a/Chapter13/README.md +++ b/Chapter13/README.md @@ -2,6 +2,22 @@ [Return to Table of Contents](../README.md) +## c13-database branch + - This branch is to replace the file folder based persistence in for member cards with a database approach + - Potentially required to address Cloud-Foundry based restarts of application, which causes the current folder to be deleted and recreated. +### Concept flow + - Database is created during admin - load process + - erase existing cards + - if database does not exist || database exists but is empty + - create database + - add record to database when create card complete + - else + - read database + - create card for each entry in database + - write card to .hfc-key-store + - fi +- This requires a manual step to drop the database when cluster is loaded + ## (1) network information - Docker and the Kubernetes deploy use different names for the CA and for the channel - Docker diff --git a/Chapter13/Z2B Wheres my code.pdf b/Chapter13/Z2B Wheres my code.pdf new file mode 100644 index 0000000..5a62a36 Binary files /dev/null and b/Chapter13/Z2B Wheres my code.pdf differ diff --git a/Chapter13/controller/env.json b/Chapter13/controller/env.json index d634cd3..2bcbbd9 100644 --- a/Chapter13/controller/env.json +++ b/Chapter13/controller/env.json @@ -31,6 +31,19 @@ "businessNetwork":"", "enrollmentSecret": "temp" }, + "cloudant": { + "username": "{your cloudant user name}", + "password": "{your cloudant password}", + "host": "{your cloudant host}", + "port": 443, + "url": "{your cloudant url}" + }, + "couchdb": { + "url": "http://localhost:5984/", + "urlBase": "localhost:5984/", + "username": "{your couchdb admin id", + "password": "{your couchdb password}" + }, "keyValStore": "/.composer-credentials", "kube_address":"0.0.0.0" } diff --git a/Chapter13/controller/restapi/features/cloudant_utils_web.js b/Chapter13/controller/restapi/features/cloudant_utils_web.js new file mode 100644 index 0000000..991a77f --- /dev/null +++ b/Chapter13/controller/restapi/features/cloudant_utils_web.js @@ -0,0 +1,501 @@ +/** + * Copyright 2015 IBM Corp. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// cloudant support +var cloudantAuth; +var cloudant_credentials; +var request = require('request'); +var cfenv = require('cfenv'); +var fs = require('fs'); +var jsonObjects = "jsonObjects.json"; +var metaData = {}; +var protocolToUse = "http"; + +function displayObjectProperties(_obj){ for(var property in _obj){ console.log("object property: "+property ); }} +function displayObjectPropertyValues(_obj){ for(var property in _obj){ console.log("object property: "+property+" with value: "+_obj[property] ); }} + +exports.w_authenticate=w_authenticate; +exports.w_create=w_create; +exports.w_drop=w_drop; +exports.w_insert=w_insert; +exports.w_update=w_update; +exports.w_delete=w_deleteItem; +exports.w_listAllDatabases=w_listAllDatabases; +exports.w_listAllDocuments=w_listAllDocuments; +exports.w_capabilities=w_capabilities; +exports.w_getMetadata=w_getMetadata; +exports.w_buildEntryPage=w_buildEntryPage; +exports.w_getDocs=w_getDocs; +exports.w_getOne=w_getOne; +exports.w_select=w_select; +exports.w_select2=w_select2; +exports.w_selectMulti=w_selectMulti; +exports.w_createBackup=w_createBackup; +exports.w_restoreTable=w_restoreTable; +exports.w_getBackups=w_getBackups; + +function getDBPath() +{ + if (cfenv.getAppEnv().isLocal) + { console.log("using local database"); + cloudant_credentials = require('../../env.json').couchdb; + protocolToUse = "http"; + var url = "http://"+cloudant_credentials.username+":"+cloudant_credentials.password+"@"+cloudant_credentials.urlBase; } + else + {console.log("using host database"); + cloudant_credentials = require('../../env.json').cloudant; + protocolToUse = "https"; + // var url = cloudant_credentials.url+"/_session"; + var url = cloudant_credentials.url+"/"; } + // console.log("getDBPath url is: "+url); + return url; +} + +function w_authenticate(req, res, next) +{ + var params = "name="+cloudant_credentials.username+"&password="+cloudant_credentials.password; + var method = "POST"; + var url = getDBPath()+"/_session"; + request({ url: url, method: method, headers: { "content-type": "application/x-www-form-urlencoded" }, form: params }, + function(error, response, body) { + if (error) { console.log("authenticate error: "+error); res.send({"error": error});} + else { cloudantAuth=response["headers"]["set-cookie"]; console.log("authentication succeeded: "+response); res.send(response);} + }); + +} +function w_create(req, res, next) +{ + // create a new database + var _name = req.body.name; + var method = "PUT"; + var url = getDBPath()+_name; + console.log("w_create: db=",_name); + request({ + url: url, + headers: {"set-cookie": cloudantAuth, 'Accept': '/'}, + method: method, + }, function(error, response, body) { + var _body = JSON.parse(body); + if ((error) || ((typeof(_body.error) != 'undefined') && (_body.error != null))) + { if ((typeof(_body.error) != 'undefined') && (_body.error != null)) { res.send({"error": _body.error});} + else {res.send({"error": error}); } + } else { res.send({"success": _body})} + }); +} +function w_drop(req, res, next) +{ + // drop a database + var _name = req.body.name; + var method = "DELETE"; + var url = getDBPath()+_name; + var _res = res; + request( { url: url, method: method }, + function(error, response, body) { if (error){ _res.send({"error": body});} else { _res.send({"success": body});} + }); +} + +function w_insert(req, res, next) +{ + // iCloudant automatically creates a unique index for each entry. + var _name = req.body.name; + var _object = req.body.content; + delete _object._rev; + var _res = res; + var method = "POST"; + var url = getDBPath()+_name; + delete _object._rev; + // console.log("w_insert url is "+url); + console.log ("w_insert for: "+ _name+ " with content: "+JSON.stringify(_object)); + request( { url: url, json: _object, method: method }, + function(error, response, body) { + if (error){console.log("error: "+ error); + _res.send({"error": error});} + else { console.log("success: "+ JSON.stringify(body)); + _res.send({"success": body}); + } + }); +} +function w_update(req, res, next) +{ + // insert JSON _object into database _name + var updateContent = req.body.content; + var _name = req.body.name; + var method = "POST"; + var object = {}; object.name = req.body.name; object.oid = req.body.oid; + var _res = res; + var url = protocolToUse+'://'+req.headers.host+'/db/getOne'; + request( { url: url, json: object, method: method }, + function(error, response, body) + { if (error){console.log("error: "+ error); _res.send({"error": error});} + else + {var orig = JSON.parse(body.success); + for(prop in updateContent){(function(_idx, _array){orig[_idx]=_array[_idx]; })(prop, updateContent)} + var method = "PUT"; + var url = getDBPath()+_name+"/"+object.oid; + console.log("update path is: "+_name+"/"+object.oid); + request( { url: url, json: orig, method: method }, + function(error, response, body) { if (error){console.log("error: "+ error); _res.send({"error": error});} + else { console.log("success: "+ JSON.stringify(body)); _res.send({"success": body});} + }); + } + }); +} + +function w_getOne(req, res, next) +{ + // select objects from database _name specified by selection criteria _selector + var _name = req.body.name; + var _oid = req.body.oid; + var method = "GET"; + var _res = res; + var url = getDBPath()+_name+"/"+_oid; + console.log("w_getOne: "+_name+"/"+_oid); + request( { url: url, method: method }, + function(error, response, body) { + if (error){ + _res.send({"error": body});} + else { + _res.send({"success": body});} + }); +} + +function w_select(req, res, next) +{ + // select objects from database _name specified by selection criteria _selector + console.log("w_select entered"); + var _name = req.body.name; + var key = req.body.key; + var view = req.body.view; + var method = "GET"; + var object = {"selector" : {"idRubric" : key}}; + var _res = res; + console.log("name: "+_name+" key: "+key+" view: "+view); + var select = ((typeof(key) == "undefined") || (key == "")) ? '/_design/views/_view/'+view : '/_design/views/_view/'+view+'?key="'+key+'"'; + console.log("select is ", select); + var url = getDBPath()+_name+ select; + //console.log(url); + request( { url: url, method: method, json: object, headers: {"Content-Type": "application/json"} }, + function(error, response, body) { if (error){ _res.send({"error": body});} else { _res.send({"success": body});} + }); +} + +function w_select2(req, res, next) +{ + // select objects from database _name specified by selection criteria _selector + console.log("w_select2 entered"); + var _name = req.body.name; + var key = req.body.key; + var view = req.body.view; + var method = "POST"; + var object = {"selector" : {"_id" : { "$gt" : 0}, "type":{"$in":key}}}; + var _res = res; + console.log("name: "+_name+" key: "+key+" view: "+view); + console.log("object: "+JSON.stringify(object)); + // var select = ((typeof(key) == "undefined") || (key == "")) ? '/_design/views/_view/'+view : '/_design/views/_view/'+view+'?key="'+key+'"'; + var select = ""; + select = "/_find"; + console.log("select is ", select); + var url = getDBPath()+_name+ select; + console.log(url); + request( { url: url, method: method, json: object, headers: {"Content-Type": "application/json"} }, + function(error, response, body) { + if (error){ _res.send({"error": body});} + else { _res.send({"success": body } );} + }); +} + +function w_selectMulti(req, res, next) +{ + // select objects from database _name specified by selection criteria _selector + console.log("w_selectMulti entered"); + var _name = req.body.name; + var keyArray = req.body.key; + var keys = ""; + for (each in keyArray){(function(_idx, _array){keys += (_idx==0)?'["'+_array[_idx]+'"': ', "'+_array[_idx]+'"'})(each, keyArray);} + keys +="]"; + var view = req.body.view; + var method = "GET"; + var object = {"keys": keyArray}; + var _res = res; + var select = '/_design/views/_view/'+view+"?key="+keys ; + console.log("object is ", object); + console.log("select is ", select); + var url = getDBPath()+_name+ select; + // console.log(url); + request( { url: url, method: method, json: object, headers: {"Content-Type": "application/json"} }, + function(error, response, body) { if (error){ _res.send({"error": body});} else { _res.send({"success": body});} + }); +} +function w_deleteItem(req, res, next) +{ + // delete object specified by _oid in database _name /$DATABASE/$DOCUMENT_ID?rev=$REV + //_name, _oid, _rev, cbfn + var _name = req.body.name; + var _oid = req.body.oid; + var _rev = req.body.rev; + var _res = res; + var method = "DELETE"; + var url = getDBPath()+_name+"/"+oid+"?rev="+_rev; + request( { url: url, method: method }, + function(error, response, body) { if (error){ _res.send({"error": body});} else { _res.send({"success": body});} + }); +} +function w_getDocs(req, res, next) +{ + var method = "GET"; + var url = getDBPath()+req.body.name+"/_all_docs?include_docs=true"; + console.log("w_getDocs path: ", url); + var _res = res; + request( { url: url, method: method }, + function(error, response, body) { if (error){console.log("w_getDocs error: ", body); _res.send({"error": body});} else { _res.send({"success": body});} + }); +} +function w_listAllDocuments(req, res, next) +{ + // list all documents in database _name + var method = "GET"; + var url = getDBPath()+"/_all_docs"; + var _res = res; + request( { url: url, method: method }, + function(error, response, body) { if (error){ _res.send({"error": body});} else { _res.send({"success": body});} + }); +} + +function w_listAllDatabases(req, res, next) +{ + // list all databases + var method = "GET"; + var url = getDBPath()+"/_all_dbs"; + var _res = res; + request( { url: url, method: method }, + function(error, response, body) { if (error){ _res.send({"error": body});} else { _res.send({"success": body});} + }); +} + +function w_capabilities(req, res, next) +{ + var _c = {}; + _c.authenticate = "function (): uses credentials in env.json file to authenticate to cloudant server"; + _c.create = "function (_name): create a new database"; + _c.drop = "function (_name): drop a database"; + _c.insert = "function (_name, _object): insert JSON _object into database _name"; + _c.update = "function (_name, _oid, _object): update JSON object specified by object _oid in database _name with new object _object"; + _c.select = "function (_name, _selector): select objects from database _name specified by selection criteria _selector"; + _c.delete = "function (_name, _oid): delete object specified by _oid in database _name"; + _c.listAllDatabases = "function (): list all databases I can access"; + _c.listAllDocuments = "function (_name): list all documents in database _name"; + _c.capabilities = "return this object with descriptors."; + _c.getMetadata = "return the jsonObjectsPretty.json file."; + res.send(_c); +} +function w_getMetadata(req, res, next) +{ + var file = jsonObjects; + var toSave = process.cwd()+"/"+file; + var contents = fs.readFileSync(toSave, 'utf8'); + metaData = JSON.parse(contents); + res.send(contents); +} +function retrieveMetaData(_name) +{ + for (each in metaData.dataModel) + {if (metaData.dataModel[each].name == _name){return(metaData.dataModel[each]);}} + return({"failed": _name+" not found"}); +} +function w_buildEntryPage(req, res, next) +{ + var pageMeta = retrieveMetaData(req.body.name); + if (typeof(pageMeta.failed) != "undefined"){return(pageMeta)} + else + { console.log(pageMeta); + var _str = "

    "+pageMeta.name+"

    "+pageMeta.description+"
    "; + var _type = req.body.type; + var _fields = ""; + for (each in pageMeta.elements) + {(function(_idx, _array){_str+=""; + })(each, pageMeta.elements)} + _str += "
    "+_array[_idx].name+""; + if (_idx > 0){_fields +=",";} + switch (_array[_idx].type) + { + case 'int': + _str += ""; + _fields += _array[_idx].name; + break; + case 'string': + _str += ""; + _fields += _array[_idx].name; + break; + case 'boolean': + _str += "True"; + _str += "False"; + _fields += _array[_idx].name+"_true,"; _fields += _array[_idx].name+"_false"; + break; + case 'email': + _str += ""; + _fields += _array[_idx].name; + break; + case 'timestamp': + // needs routine to get timestamp + var _tStamp = new Date(Date.now()); + _str += "
    "+_tStamp.toISOString()+"
    "; + _fields += _array[_idx].name; + break; + case 'JSON': + _str += ""; + _fields += _array[_idx].name; + break; + case 'index': + _str += "
    Defined when inserted
    "; + _fields += _array[_idx].name; + break; + default: + _str += "
    "+_array[_idx].type+" is not a recognized type
    "; + _fields += _array[_idx].name; + break; + } + _str +="
    _rev"+"
    Defined when inserted
    "; + _fields += ",_rev"; + console.log(_fields); + _str += "Insert New Document
    \n"; + _str += " \n"; + console.log(_str); + res.send(_str); + } +} +function w_createBackup(req, res, next) +{ + var _object = {}; + _object.name = (typeof(req.body.name)=="undefined") ? "" : req.body.name; + var _res = res; + var method = "POST"; + var url = protocolToUse+'://'+req.headers.host+'/db/getDocs'; + console.log("w_createBackup object: ", _object); + // console.log("w_createBackup path: ", url); + request( { url: url, json: _object, method: method }, + function(error, response, body) + { console.log("request completed for table: "+_object.name); + if (error) + {console.log("error: "+ error); _res.send({"error": error});} + else + { +// console.log("success: response ", response); + console.log("success: body ", body.success); + var fileName = process.cwd()+"/HTML/backups/"+'Backup_'; + fileName += (_object.name == "") ? "allFiles" : _object.name; + fileName +="_"+getTimeStamp()+".json"; + console.log("creating backup at: ", fileName); + var rows = JSON.parse(body.success).rows; + var _views = '"views": ['; var viewNum = 0; + var _str = "["; + for (each in rows) + {(function(_idx, _array) + {if(_array[_idx].doc._id != '_design/views') + { if(_idx>0){_str+=", ";} + _str+=JSON.stringify(_array[_idx].doc); console.log(JSON.stringify(_array[_idx].doc)); + } + else { + if(viewNum>0){_views+=", ";} _views += '{ "_id": "_design/views", "views":' +JSON.stringify(_array[_idx].doc.views)+'}'; + } + })(each, rows)} + _str+="]"; _views += "]"; + fs.writeFileSync(fileName, '{"table" : "'+_object.name+'", "date": "'+getTimeStamp()+'", "rows": '+_str+', '+_views+'}', 'utf8'); + _res.send(JSON.parse(body.success).rows);} + }); +} +function w_restoreTable(req, res, next) +{ + console.log("w_restoreTable entered for "+req.body.name); + var fileName = process.cwd()+"/HTML/backups/"+req.body.name; + var restoreObject =JSON.parse(fs.readFileSync(fileName)); + console.log("starting restore for table: "+restoreObject.table+" created on: "+restoreObject.date); + console.log("restore data: "+JSON.stringify(restoreObject.rows)); + // drop existing table + var object = {}; object.name = restoreObject.table ; + var _res = res; + var method = "POST"; + var url = protocolToUse+'://'+req.headers.host+'/db/dropTable'; + request( { url: url, json: object, method: method }, + function(error, response, body) + { console.log("request to drop table: "+object.name+" completed"); + if (error){console.log("error: "+ error); _res.send({"error": error});} + else + {console.log("drop table: result: "+response); + // create new table + var url = protocolToUse+'://'+req.headers.host+'/db/createTable'; + request( { url: url, json: object, method: method }, + function(error, response, body) + { console.log("request to create table: "+object.name+" completed"); + if (error){console.log("error: "+ error); _res.send({"error": error});} + else + {console.log("create table: result: "+response); + var url = protocolToUse+'://'+req.headers.host+'/db/insert'; + for (each in restoreObject.rows) + { console.log("["+each+"] restoring row: "+JSON.stringify(restoreObject.rows[each])); + var _object = object; _object.content = restoreObject.rows[each]; + if(process.env.SNDEMAIL && process.env.SNDEMAIL!== '') { + _object.content.email = process.env.SNDEMAIL; + } + console.log("Restoring with : ", JSON.stringify(_object, null , 4)); + request( { url: url, json: _object, method: method }, + function(error, response, body) { console.log("row restored: "+response);}); + } + for (each in restoreObject.views) + { console.log("["+each+"] restoring row: "+JSON.stringify(restoreObject.views[each])); + var _object = {}; _object.name = object.name; _object.content = restoreObject.views[each]; + if(process.env.SNDEMAIL && process.env.SNDEMAIL!== '') { + _object.content.email = process.env.SNDEMAIL; + } + + console.log("Restoring with : ", JSON.stringify(_object, null , 4)); + request( { url: url, json: _object, method: method }, + function(error, response, body) { console.log("view restored: "+response);}); + } + } + }); + } + }); +} +function w_getBackups(req, res, next) +{ + var loc = process.cwd()+"/HTML/backups/"; + var files = fs.readdirSync(loc); + console.log(files); + res.send(files); +} +function getTimeStamp() {return(new Date(Date.now()).toISOString().replace(/:/g, '.'));} diff --git a/Chapter13/controller/restapi/features/composer/Z2B_Services.js b/Chapter13/controller/restapi/features/composer/Z2B_Services.js index 07004e6..eab9aa4 100644 --- a/Chapter13/controller/restapi/features/composer/Z2B_Services.js +++ b/Chapter13/controller/restapi/features/composer/Z2B_Services.js @@ -16,6 +16,7 @@ let fs = require('fs'); let path = require('path'); const sleep = require('sleep'); +var request = require('request'); // const ws = require('websocket'); // const http = require('http'); @@ -26,7 +27,18 @@ const cfenv = require('cfenv'); const appEnv = cfenv.getAppEnv(); const util = require('./Z2B_Utilities'); app.set('port', appEnv.port); - +let protocolToUse; +if (cfenv.getAppEnv().isLocal) +{ + console.log(" Z2B is running locally"); + protocolToUse = "http"; +} +else +{ + console.log("Z2B is running in cloud"); + protocolToUse = "https"; +} +const restartDate = new Date().toISOString(); /** @@ -125,10 +137,10 @@ let Z2Blockchain = { */ loadTransaction: function (_con, _item, _id, businessNetworkConnection) { - let method = 'loadTransaction'; + let methodName = 'loadTransaction'; return businessNetworkConnection.submitTransaction(_item) .then(() => { - console.log(method+': order '+_id+' successfully added '); + console.log(methodName+': order '+_id+' successfully added '); this.send(_con, 'Message', 'Order '+_id+' successfully added'); }) .catch((error) => { @@ -150,7 +162,7 @@ let Z2Blockchain = { */ addOrder: function (_con, _order, _registry, _createNew, _bnc) { - let method = 'addOrder'; + let methodName = 'addOrder'; return _registry.add(_order) .then(() => { this.loadTransaction(_con, _createNew, _order.orderNumber, _bnc); @@ -160,7 +172,7 @@ let Z2Blockchain = { {console.log(_order.orderNumber+' addOrder retrying assetRegistry.add for: '+_order.orderNumber); this.addOrder(_con, _order, _registry, _createNew, _bnc); } - else {console.log(method+' error with assetRegistry.add', error);} + else {console.log(methodName+' error with assetRegistry.add', error);} }); }, @@ -174,18 +186,146 @@ let Z2Blockchain = { */ bindIdentity: function (_con, _id, _cert, _bnc) { - let method = 'bindIdentity'; - console.log(method+' retrying bindIdentity for: '+_id); + let methodName = 'bindIdentity'; + console.log(methodName+' retrying bindIdentity for: '+_id); return _bnc.bindIdentity(_id, _cert) .then(() => { - console.log(method+' Succeeded for: '+_id); + console.log(methodName+' Succeeded for: '+_id); }) .catch((error) => { if (error.message.search('MVCC_READ_CONFLICT') !== -1) {console.log(' bindIdentity retrying _bnc.bindIdentity(_id, _cert) for: '+_id); this.bindIdentity(_con, _id, _cert, _bnc); } - else {console.log(method+' error with _bnc.bindIdentity(_id, _cert) for: '+_id+' with error: ', error);} + else {console.log(methodName+' error with _bnc.bindIdentity(_id, _cert) for: '+_id+' with error: ', error);} + }); + }, +/** + * saves the member table with ids and secrets + * @param {string} _dbName - string, name of database to access + * @param {String} _key - key field for this record + * @param {String} _host - host url + */ + getThisMember: function (_locals, _dbName, _key, _host) + { + let methodName = 'getThisMember'; + console.log(methodName+' entered for '+_dbName+' with key: '+_key); + return new Promise(function(resolve, reject) + { + let options = {}; + options.name = _dbName; + options.oid = _key; + var url = protocolToUse+'://'+_host+'/db/getOne'; + var method = "POST"; + console.log(methodName+' requesting from url: '+url+' with options: ', options); + request( { url: url, json: options, method: method }, + function(error, response, body) + { + if (typeof(body.success) != 'undefined') + {console.log(methodName+" "+_key+" retrieved successfully"); resolve(body.success);} + else + {console.log(methodName+' error body: ', body); reject(body);} + }); + }); +}, +/** + * saves the member table with ids and secrets + * @param {string} _dbName - string, name of database to access + * @param {JSON} _item - data to store in dbName + * @param {String} _key - key field for this record + * @param {String} _host - host url + */ +saveToDB: function (_dbName, _item, _key, _host) +{ + let methodName = 'saveToDB'; + let _this = this; + _item.lastUpdated=restartDate; + let options = {}; + options.name = _dbName; + options.content = _item; + options.content._id = _key; + var url = protocolToUse+'://'+_host+'/db/insert'; + var method = "POST"; + request( { url: url, json: options, method: method }, + function(error, response, body) + { + if ((typeof(body.success) != 'undefined') && (body.success.ok == 'true')) + {console.log(body.id+" stored in db successfully");} + else + { + // { success: { error: 'conflict', reason: 'Document update conflict.' } } + // this occurs when the network has been reloaded and the database still has the previous + // version information + if ((typeof(body.success.error) != 'undefined') && (body.success.error == 'conflict')) + { + _this.updateDB (_dbName, _item, _key, _host) + } + else {console.log(methodName+' error body: ', body);} + } + }); +}, +/** + * saves the member table with ids and secrets + * @param {string} _dbName - string, name of database to access + * @param {JSON} _item - data to store in dbName + * @param {String} _key - key field for this record + * @param {String} _host - host url + */ + updateDB: function (_dbName, _item, _key, _host) + { + let methodName = 'updateDB'; + _item.lastUpdated=restartDate; + let options = {}; + options.name = _dbName; + options.content = _item; + options.oid = _key; + var url = protocolToUse+'://'+_host+'/db/update'; + var method = "POST"; + request( { url: url, json: options, method: method }, + function(error, response, body) + { + // updateDB error body: { success: { ok: true, id: 'abdul@cognitiveadvantageinc.com', rev: '2-b42cdc8bfa78e8e62d11947e4357a0d4' } } + if ((typeof(body.success) != 'undefined') && (body.success.ok == true)) + {console.log(body.success.id+" updated in db successfully");} + else + { + console.log(methodName+' error body: ', body); + } + }); + }, +/** + * saves the member table with ids and secrets + * @param {string} _dbName - string, name of database to create if missing + * @param {String} _host - host url + */ + connectToDB: function (_dbName, _host) + { + let methodName = 'connectToDB'; + return new Promise(function(resolve, reject) + { + let options = {}; + options.name = _dbName; + var url = protocolToUse+'://'+_host+'/db/createTable'; + var method = "POST"; + request( { url: url, json: options, method: method }, + function(error, response, body) + { + if ((typeof(body.success) != 'undefined') && (body.success.ok == 'true')) + {console.log(_dbName+" created successfully"); resolve("success");} + else + { + if ((typeof(body.error) != 'undefined') && (body.error == 'file_exists')) + { + console.log(_dbName+' database already exists'); + resolve("success"); + } + else + { + console.log(methodName+' error is: ', error); + reject(error); + } + } + }); }); }, diff --git a/Chapter13/controller/restapi/features/composer/autoLoad.js b/Chapter13/controller/restapi/features/composer/autoLoad.js index e8d1c40..5c4fb38 100644 --- a/Chapter13/controller/restapi/features/composer/autoLoad.js +++ b/Chapter13/controller/restapi/features/composer/autoLoad.js @@ -26,23 +26,46 @@ const fs = require('fs'); const path = require('path'); const _home = require('os').homedir(); const hlc_idCard = require('composer-common').IdCard; +const request = require('request'); const AdminConnection = require('composer-admin').AdminConnection; const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const financeCoID = 'easymoney@easymoneyinc.com'; - +const cfenv = require('cfenv'); const svc = require('./Z2B_Services'); const config = require('../../../env.json'); -const admin_connection = require('../../../connection.json'); +// 9/12/18 change to read connection.json from PeerAdmin@hlfv1 card +const admin_connection = require('./creds/cards/PeerAdmin@hlfv1/connection.json'); admin_connection.keyValStore = _home+config.keyValStore; - +const memberDB = 'z2b_members'; +const homedir = require('os').homedir(); +const CLIENT_DATA = 'client-data' +const basePath = homedir+'/.composer/'+CLIENT_DATA+'/'; +let protocolToUse; +if (cfenv.getAppEnv().isLocal) + { protocolToUse = "http"; } +else + { protocolToUse = "https"; } /** * itemTable and memberTable are used by the server to reduce load time requests * for member secrets and item information */ let itemTable = new Array(); let memberTable = new Array(); +/** + * getLastRestart retrieves a timestamp for the last time the system was restarted + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + */ +exports.getLastRestart = function( req, res, next) +{ + let methodName = 'getLastRestart'; + const _id = 'noop@dummyProvider'; + svc.getThisMember(req.app.locals, memberDB, _id, req.headers.host) + .then((_res) => {res.send({result: 'success', timeStamp: JSON.parse(_res).lastUpdated}); }); +} /** * autoLoad reads the memberList.json file from the Startup folder and adds members, * executes the identity process, and then loads orders @@ -54,156 +77,216 @@ let memberTable = new Array(); * @function */ exports.autoLoad = function(req, res, next) { - // get the autoload file - let newFile = path.join(path.dirname(require.main.filename),'startup','memberList.json'); - let startupFile = JSON.parse(fs.readFileSync(newFile)); - // connect to the network - let businessNetworkConnection; - let factory; let participant; -// svc.createMessageSocket(); -// socketAddr = svc.m_socketAddr; - let adminConnection = new AdminConnection(); - // connection prior to V0.15 - // adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW) - // connection in v0.15 - adminConnection.connect(config.composer.adminCard) - .then(() => { - // a businessNetworkConnection is required to add members - businessNetworkConnection = new BusinessNetworkConnection(); + let methodName = 'autoLoad'; + // connect to the member table + svc.connectToDB(memberDB, req.headers.host) + .then((_conn_res) => { + // get the autoload file + let newFile = path.join(path.dirname(require.main.filename),'startup','memberList.json'); + let startupFile = JSON.parse(fs.readFileSync(newFile)); + // connect to the network + let businessNetworkConnection; + let factory; let participant; + // svc.createMessageSocket(); + // socketAddr = svc.m_socketAddr; + let adminConnection = new AdminConnection(); // connection prior to V0.15 - // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // adminConnection.connect(config.composer.connectionProfile, config.composer.adminID, config.composer.adminPW) // connection in v0.15 - return businessNetworkConnection.connect(config.composer.adminCard) + adminConnection.connect(config.composer.adminCard) .then(() => { - // a factory is required to build the member object - factory = businessNetworkConnection.getBusinessNetwork().getFactory(); - //iterate through the list of members in the memberList.json file and - // first add the member to the network, then create an identity for - // them. This generates the memberList.txt file later used for - // retrieving member secrets. - for (let each in startupFile.members) - {(function(_idx, _arr) - { - // the participant registry is where member information is first stored - // there are individual registries for each type of participant, or member. - // In our case, that is Buyer, Seller, Provider, Shipper, FinanceCo - return businessNetworkConnection.getParticipantRegistry(config.composer.NS+'.'+_arr[_idx].type) - .then(function(participantRegistry){ - return participantRegistry.get(_arr[_idx].id) - .then((_res) => { - console.log('['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.send(req.app.locals, 'Message', '['+_idx+'] member with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - }) - .catch((error) => { - participant = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); - participant.companyName = _arr[_idx].companyName; - participantRegistry.add(participant) - .then(() => { - console.log('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); - svc.send(req.app.locals, 'Message', '['+_idx+'] '+_arr[_idx].companyName+' successfully added'); - }) - .then(() => { - // an identity is required before a member can take action in the network. - // V0.14 - // return businessNetworkConnection.issueIdentity(config.composer.NS+'.'+_arr[_idx].type+'#'+_arr[_idx].id, _arr[_idx].pw) - // V0.15 - console.log('issuing identity for: '+config.composer.NS+'.'+_arr[_idx].type+'#'+_arr[_idx].id); - return businessNetworkConnection.issueIdentity(config.composer.NS+'.'+_arr[_idx].type+'#'+_arr[_idx].id, _arr[_idx].id) - .then((result) => { - console.log('_arr[_idx].id: '+_arr[_idx].id); - console.log('result.userID: '+result.userID); - let _mem = _arr[_idx]; - _mem.secret = result.userSecret; - _mem.userID = result.userID; - memberTable.push(_mem); - // svc.saveMemberTable(memberTable); + // a businessNetworkConnection is required to add members + businessNetworkConnection = new BusinessNetworkConnection(); + // connection prior to V0.15 + // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) + // connection in v0.15 + return businessNetworkConnection.connect(config.composer.adminCard) + .then(() => { + // a factory is required to build the member object + factory = businessNetworkConnection.getBusinessNetwork().getFactory(); + //iterate through the list of members in the memberList.json file and + // first add the member to the network, then create an identity for + // them. This generates the memberList.txt file later used for + // retrieving member secrets. + for (let each in startupFile.members) + {(function(_idx, _arr) + { + // the participant registry is where member information is first stored + // there are individual registries for each type of participant, or member. + // In our case, that is Buyer, Seller, Provider, Shipper, FinanceCo + return businessNetworkConnection.getParticipantRegistry(config.composer.NS+'.'+_arr[_idx].type) + .then(function(participantRegistry){ + return participantRegistry.get(_arr[_idx].id) + .then((_res) => { + svc.getThisMember(req.app.locals, memberDB, _arr[_idx].id, req.headers.host) + .then((_res) => { + console.log(methodName+' svc.getThisMember('+_arr[_idx].id+') _res: ', _res); + let member = JSON.parse(_res); + let options = {}; + options.registry = member.type; let _meta = {}; for (each in config.composer.metaData) {(function(_idx, _obj) {_meta[_idx] = _obj[_idx]; })(each, config.composer.metaData); } _meta.businessNetwork = config.composer.network; - _meta.userName = result.userID; - _meta.enrollmentSecret = result.userSecret; + _meta.userName = member.id; + _meta.enrollmentSecret = member.secret; + console.log(methodName+' svc.getThisMember('+_arr[_idx].id+') _meta: ', _meta); let tempCard = new hlc_idCard(_meta, admin_connection); - return adminConnection.importCard(result.userID, tempCard) + return adminConnection.importCard(member.id, tempCard) + .then(() => { + let currentMemberPath = path.join(basePath,member.id); + fs.mkdirSync(currentMemberPath); + for (let i=0; i<3; i++) + {(function(_idx) + {console.log(methodName+' looping on ['+_idx+'] is: '+member[CLIENT_DATA+_idx].name); + let _path = path.join(basePath,member.id,member[CLIENT_DATA+_idx].name); + fs.writeFileSync(_path, member[CLIENT_DATA+_idx].file); + })(i) + } + }) + .catch((error) => {console.log(methodName+' adminConnection.importCard for '+member.id+' failed with error: ', error);}) + }) + .catch((_error) => { + console.log(methodName+' error: ',_error); + }); + }) + .catch((error) => { + participant = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); + participant.companyName = _arr[_idx].companyName; + participantRegistry.add(participant) + .then(() => { + console.log('['+_idx+'] '+_arr[_idx].companyName+' successfully added'); + svc.send(req.app.locals, 'Message', '['+_idx+'] '+_arr[_idx].companyName+' successfully added'); + }) + .then(() => { + // an identity is required before a member can take action in the network. + // V0.14 + // return businessNetworkConnection.issueIdentity(config.composer.NS+'.'+_arr[_idx].type+'#'+_arr[_idx].id, _arr[_idx].pw) + // V0.15 + console.log('issuing identity for: '+config.composer.NS+'.'+_arr[_idx].type+'#'+_arr[_idx].id); + return businessNetworkConnection.issueIdentity(config.composer.NS+'.'+_arr[_idx].type+'#'+_arr[_idx].id, _arr[_idx].id) + .then((result) => { + console.log('_arr[_idx].id: '+_arr[_idx].id); + console.log('result.userID: '+result.userID); + let _mem = _arr[_idx]; + _mem.secret = result.userSecret; + _mem.userID = result.userID; + memberTable.push(_mem); + //svc.saveToDB(memberDB, _mem, result.userID, req.headers.host); + //svc.saveMemberTable(memberTable); + let _meta = {}; + for (each in config.composer.metaData) + {(function(_idx, _obj) {_meta[_idx] = _obj[_idx]; })(each, config.composer.metaData); } + _meta.businessNetwork = config.composer.network; + _meta.userName = result.userID; + _meta.enrollmentSecret = result.userSecret; + let tempCard = new hlc_idCard(_meta, admin_connection); + return adminConnection.importCard(result.userID, tempCard) .then ((_res) => { - if (_res) {console.log('card updated');} else {console.log('card imported');} + if (_res) + {console.log(methodName+' '+result.userID+' card updated');} + else {console.log(methodName+' '+result.userID+' card imported');} + let bnc = new BusinessNetworkConnection(); + return bnc.connect(_arr[_idx].id) + .then(() => { + console.log(methodName+' businessNetworkConnection.connect() succeeded'); + return bnc.ping() + .then((_msg) => { + console.log(methodName+' businessNetworkConnection.ping() succeeded'); + // retrieve CLIENT_DATA info and preserve it + let currentMemberPath = path.join(basePath,result.userID); + let fileList = fs.readdirSync(currentMemberPath); + for (each in fileList) + {(function(_each, _files) + {console.log(methodName+' looping on _files['+_each+'] is: '+_files[_each]); + let _path = path.join(basePath,result.userID,_files[_each]); + let _file=fs.readFileSync(_path, 'utf8'); + _mem[CLIENT_DATA+_each]={'name': _files[_each], 'file': _file};})(each, fileList) + } + svc.saveToDB(memberDB, _mem, result.userID, req.headers.host); + }) + .catch((error) => { console.log(methodName+' businessNetworkConnection.ping() failed. error: ',error); bnc.disconnect(); }); + }) + .catch((error) => { console.log(methodName+' businessNetworkConnection.connect() failed. error: ',error); bnc.disconnect(); }); }) .catch((error) => { console.error('adminConnection.importCard failed. ',error.message); }); + }) + .catch((error) => { + console.error('create id for '+_arr[_idx].id+'failed. ',error.message); + }); }) - .catch((error) => { - console.error('create id for '+_arr[_idx].id+'failed. ',error.message); - }); - }) - .catch((error) => {console.log(_arr[_idx].companyName+' add failed',error.message);}); - }); - }) - .catch((error) => {console.log('error with getParticipantRegistry', error.message);}); - })(each, startupFile.members); - } - // iterate through the order objects in the memberList.json file. - for (let each in startupFile.items){(function(_idx, _arr){itemTable.push(_arr[_idx]);})(each, startupFile.items);} - svc.saveItemTable(itemTable); - for (let each in startupFile.assets) - {(function(_idx, _arr) - { - // each type of asset, like each member, gets it's own registry. Our application - // has only one type of asset: 'Order' - return businessNetworkConnection.getAssetRegistry(config.composer.NS+'.'+_arr[_idx].type) - .then((assetRegistry) => { - return assetRegistry.get(_arr[_idx].id) - .then((_res) => { - console.log('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); - svc.send(req.app.locals, 'Message', '['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + .catch((error) => {console.log(_arr[_idx].companyName+' add failed',error.message);}); + }); }) - .catch((error) => { - // first, an Order Object is created - let order = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); - order = svc.createOrderTemplate(order); - let _tmp = svc.addItems(_arr[_idx], itemTable); - order.items = _tmp.items; - order.amount = _tmp.amount; - order.orderNumber = _arr[_idx].id; - // then the buy transaction is created - const createNew = factory.newTransaction(config.composer.NS, 'CreateOrder'); - order.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); - order.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); - order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummyProvider'); - order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummyShipper'); - order.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); - createNew.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); - createNew.order = factory.newRelationship(config.composer.NS, 'Order', order.$identifier); - createNew.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); - createNew.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); - createNew.amount = order.amount; - // then the order is added to the asset registry. - return assetRegistry.add(order) - .then(() => { - // then a createOrder transaction is processed which uses the chaincode - // establish the order with it's initial transaction state. - svc.loadTransaction(req.app.locals, createNew, order.orderNumber, businessNetworkConnection); + .catch((error) => {console.log('error with getParticipantRegistry', error.message);}); + })(each, startupFile.members); + } + // iterate through the order objects in the memberList.json file. + for (let each in startupFile.items){(function(_idx, _arr){itemTable.push(_arr[_idx]);})(each, startupFile.items);} + svc.saveItemTable(itemTable); + for (let each in startupFile.assets) + {(function(_idx, _arr) + { + // each type of asset, like each member, gets it's own registry. Our application + // has only one type of asset: 'Order' + return businessNetworkConnection.getAssetRegistry(config.composer.NS+'.'+_arr[_idx].type) + .then((assetRegistry) => { + return assetRegistry.get(_arr[_idx].id) + .then((_res) => { + console.log('['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); + svc.send(req.app.locals, 'Message', '['+_idx+'] order with id: '+_arr[_idx].id+' already exists in Registry '+config.composer.NS+'.'+_arr[_idx].type); }) .catch((error) => { - // in the development environment, because of how timing is set up, it is normal to - // encounter the MVCC_READ_CONFLICT error. This is a database timing error, not a - // logical transaction error. - if (error.message.search('MVCC_READ_CONFLICT') !== -1) - {console.log('AL: '+_arr[_idx].id+' retrying assetRegistry.add for: '+_arr[_idx].id); - svc.addOrder(req.app.locals, order, assetRegistry, createNew, businessNetworkConnection); - } - else {console.log('error with assetRegistry.add', error.message);} + // first, an Order Object is created + let order = factory.newResource(config.composer.NS, _arr[_idx].type, _arr[_idx].id); + order = svc.createOrderTemplate(order); + let _tmp = svc.addItems(_arr[_idx], itemTable); + order.items = _tmp.items; + order.amount = _tmp.amount; + order.orderNumber = _arr[_idx].id; + // then the buy transaction is created + const createNew = factory.newTransaction(config.composer.NS, 'CreateOrder'); + order.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); + order.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); + order.provider = factory.newRelationship(config.composer.NS, 'Provider', 'noop@dummyProvider'); + order.shipper = factory.newRelationship(config.composer.NS, 'Shipper', 'noop@dummyShipper'); + order.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); + createNew.financeCo = factory.newRelationship(config.composer.NS, 'FinanceCo', financeCoID); + createNew.order = factory.newRelationship(config.composer.NS, 'Order', order.$identifier); + createNew.buyer = factory.newRelationship(config.composer.NS, 'Buyer', _arr[_idx].buyer); + createNew.seller = factory.newRelationship(config.composer.NS, 'Seller', _arr[_idx].seller); + createNew.amount = order.amount; + // then the order is added to the asset registry. + return assetRegistry.add(order) + .then(() => { + // then a createOrder transaction is processed which uses the chaincode + // establish the order with it's initial transaction state. + svc.loadTransaction(req.app.locals, createNew, order.orderNumber, businessNetworkConnection); + }) + .catch((error) => { + // in the development environment, because of how timing is set up, it is normal to + // encounter the MVCC_READ_CONFLICT error. This is a database timing error, not a + // logical transaction error. + if (error.message.search('MVCC_READ_CONFLICT') !== -1) + {console.log('AL: '+_arr[_idx].id+' retrying assetRegistry.add for: '+_arr[_idx].id); + svc.addOrder(req.app.locals, order, assetRegistry, createNew, businessNetworkConnection); + } + else {console.log('error with assetRegistry.add', error.message);} + }); }); - }); - }) - .catch((error) => {console.log('error with getParticipantRegistry', error.message);}); - })(each, startupFile.assets); - } + }) + .catch((error) => {console.log('error with getParticipantRegistry', error.message);}); + })(each, startupFile.assets); + } + }) + .catch((error) => {console.log('error with business network Connect', error.message);}); }) - .catch((error) => {console.log('error with business network Connect', error.message);}); + .catch((error) => {console.log('error with adminConnect', error.message);}); + res.send({'result': 'Success'}); }) - .catch((error) => {console.log('error with adminConnect', error.message);}); - res.send({'result': 'Success'}); + .catch((error) => {console.log(methodName+' svc.connectToDB('+memberDB+', req.headers.host); failed with error: ', error);}); }; /** diff --git a/Chapter13/controller/restapi/features/composer/hlcAdmin.js b/Chapter13/controller/restapi/features/composer/hlcAdmin.js index 5011f11..baef8a8 100644 --- a/Chapter13/controller/restapi/features/composer/hlcAdmin.js +++ b/Chapter13/controller/restapi/features/composer/hlcAdmin.js @@ -24,7 +24,9 @@ const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefi const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const config = require('../../../env.json'); const NS = 'org.acme.Z2BTestNetwork'; -const admin_connection = require('../../../connection.json'); +// 9/12/18 change to read connection.json from PeerAdmin@hlfv1 card +const admin_connection = require('./creds/cards/PeerAdmin@hlfv1/connection.json'); +// const admin_connection = require('../../../connection.json'); admin_connection.keyValStore = _home+config.keyValStore; /** @@ -422,6 +424,8 @@ exports.checkCard = function(req, res, next) { * @function */ exports.createCard = function(req, res, next) { + let methodName = 'createCard'; + console.log(methodName+' entered for: ', req.body.id); let adminConnection = new AdminConnection(); let _meta = {}; for (let each in config.composer.metaData) @@ -435,7 +439,14 @@ exports.createCard = function(req, res, next) { return adminConnection.importCard(req.body.id, tempCard) .then ((_res) => { let _msg = ((_res) ? 'card updated' : 'card imported'); console.log('create Card succeeded:'+_msg); - res.send({'result': 'success', 'card': _msg}); + let businessNetworkConnection = new BusinessNetworkConnection(); + return businessNetworkConnection.connect(req.body.id) + .then(() => { + return businessNetworkConnection.ping() + .then((_msg) => { businessNetworkConnection.disconnect(); res.send({'result': 'success', 'card': _msg}); }) + .catch((error) => { console.log(methodName+' businessNetworkConnection.ping() failed. error: ',error); businessNetworkConnection.disconnect(); res.send({'result': 'failed', 'card': error});}); + }) + .catch((error) =>{ console.log(methodName+' businessNetworkConnection.connect('+req.body.id+') failed. error: ',error); res.send({'result': 'failed', 'card': error});}); }) .catch((error) => { console.error('adminConnection.importCard failed. ',error.message); @@ -618,6 +629,7 @@ exports.removeMember = function(req, res, next) { // connection prior to V0.15 // return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW) // connection in v0.15 + /* return businessNetworkConnection.connect(config.composer.adminCard) .then(() => { return businessNetworkConnection.getParticipantRegistry(NS+'.'+req.body.registry) @@ -637,6 +649,7 @@ exports.removeMember = function(req, res, next) { .catch((error) => {console.log('error with getParticipantRegistry', error); res.send(error.message);}); }) .catch((error) => {console.log('error with businessNetworkConnection', error); res.send(error.message);}); + */ }; /** @@ -692,4 +705,20 @@ exports.getHistory = function(req, res, next) { */ exports.getKubeAddress = function(req, res, next) { res.send(config.kube_address); -}; \ No newline at end of file +}; +/** + * check to see if the system has been loaded with members yet. + * memberStatus.JSON: BUILD_MEMBERS === 'NOT STARTED', the autoLoad process has not yet been run + * memberStatus.JSON: BUILD_MEMBERS === 'COMPLETE', the autoLoad process has been run to completion + * Folder abby@kidfriendlyinc.com exists, this system has not yet been restarted since autoLoad was run to completion + * Folder abby@kidfriendlyinc.com does not exist, this system has been restarted since autoLoad was run to completion + * + * ===> Not Yet Active <=== + * @param {express.req} req - the inbound request object from the client + * @param {express.res} res - the outbound response object for communicating back to client + * @param {express.next} next - an express service to enable post processing prior to responding to the client + * @function + */ +exports.checkLoadStatus = function(req, res, next) { + res.send({status: ''}); +}; diff --git a/Chapter13/controller/restapi/features/composer/queryBlockChain.js b/Chapter13/controller/restapi/features/composer/queryBlockChain.js index 04498ef..340ac90 100644 --- a/Chapter13/controller/restapi/features/composer/queryBlockChain.js +++ b/Chapter13/controller/restapi/features/composer/queryBlockChain.js @@ -28,6 +28,8 @@ const svc = require('./Z2B_Services'); // const util = require('./Z2B_Utilities'); // const financeCoID = 'easymoney@easymoneyinc.com'; const config = require('../../../env.json'); +// 9/12/18 change to read connection.json from PeerAdmin@hlfv1 card +const admin_connection = require('./creds/cards/PeerAdmin@hlfv1/connection.json'); const hlf1_profile = require('../../../connection.json'); let chainEvents = false; @@ -73,18 +75,18 @@ exports.getChainInfo = function(req, res, next) // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial if (user === null || user === undefined || user.isEnrolled() === false) { console.error('User not defined, or not enrolled - error');} - if (HOST_NAME.slice(0,9) === 'localhost') + if (admin_connection.channel === 'composerchannel') { - console.log(method+" running locally"); + console.log(method+" running against Docker images"); channel = client.newChannel(config.fabric.channelName); channel.addPeer(client.newPeer(config.fabric.peerRequestURL)); channel.addOrderer(client.newOrderer(config.fabric.ordererURL)); }else { - console.log(method+" running locally"); - channel = client.newChannel(hlf1_profile.channel); - channel.addPeer(client.newPeer(hlf1_profile.peers[0].requestURL)); - channel.addOrderer(client.newOrderer(hlf1_profile.orderers[0].url)); + console.log(method+" running against kubernetes immages"); + channel = client.newChannel(admin_connection.channel); + channel.addPeer(client.newPeer(admin_connection.peers[0].requestURL)); + channel.addOrderer(client.newOrderer(admin_connection.orderers[0].url)); } }) .then(() => { @@ -142,17 +144,21 @@ exports.getChainEvents = function(req, res, next) // place where the remote addresseses are loaded (from hlf1_profile) will need to be replaced with the local profiles. // You will find the local profile definitions in the env.json file and use of these definitions can be found in Chapter 12 of this tutorial // get the channel name - channel = client.newChannel(hlf1_profile.channel); + if (admin_connection.channel === 'composerchannel') + {console.log(method+" running against Docker images");} + else + {console.log(method+" running against kubernetes images");} + channel = client.newChannel(admin_connection.channel); //get the request URL for the Peer0 container - channel.addPeer(client.newPeer(hlf1_profile.peers[0].requestURL)); + channel.addPeer(client.newPeer(admin_connection.peers[0].requestURL)); // get the orderer URL - channel.addOrderer(client.newOrderer(hlf1_profile.orderers[0].url)); + channel.addOrderer(client.newOrderer(admin_connection.orderers[0].url)); // change Admin in following line to admin var pemPath = path.join(__dirname,'creds','ca.pem'); var adminPEM = fs.readFileSync(pemPath).toString(); var bcEvents = new hfcEH(client); - bcEvents.setPeerAddr(hlf1_profile.peers[0].eventURL, {pem: adminPEM}); - bcEvents.registerBlockEvent( + bcEvents.setPeerAddr(admin_connection.peers[0].eventURL, {pem: adminPEM}); + bcEvents.registerBlockEvent( function(event){svc.send(req.app.locals, 'BlockChain', event);}, function(error){console.log(method+': registerBlockEvent error: ', error);} ); diff --git a/Chapter13/controller/restapi/router.js b/Chapter13/controller/restapi/router.js index 6703a00..9a91733 100644 --- a/Chapter13/controller/restapi/router.js +++ b/Chapter13/controller/restapi/router.js @@ -14,17 +14,18 @@ 'use strict'; -let express = require('express'); -let router = express.Router(); -let format = require('date-format'); +var express = require('express'); +var router = express.Router(); +var format = require('date-format'); -let multi_lingual = require('./features/multi_lingual'); -let resources = require('./features/resources'); -let getCreds = require('./features/getCredentials'); -let hlcAdmin = require('./features/composer/hlcAdmin'); -let hlcClient = require('./features/composer/hlcClient'); -let setup = require('./features/composer/autoLoad'); -let hlcFabric = require('./features/composer/queryBlockChain'); +var multi_lingual = require('./features/multi_lingual'); +var resources = require('./features/resources'); +var getCreds = require('./features/getCredentials'); +var hlcAdmin = require('./features/composer/hlcAdmin'); +var hlcClient = require('./features/composer/hlcClient'); +var setup = require('./features/composer/autoLoad'); +var hlcFabric = require('./features/composer/queryBlockChain'); +var noSQL = require('./features/cloudant_utils_web'); router.get('/fabric/getChainInfo', hlcFabric.getChainInfo); @@ -32,10 +33,11 @@ router.get('/fabric/getChainEvents', hlcFabric.getChainEvents); router.get('/fabric/getHistory', hlcAdmin.getHistory); router.post('/setup/autoLoad*', setup.autoLoad); +router.get('/setup/getLastRestart*', setup.getLastRestart); router.get('/composer/client/initEventRegistry*', hlcClient.init_z2bEvents); module.exports = router; -let count = 0; +var count = 0; /** * This is a request tracking function which logs to the terminal window each request coming in to the web serve and * increments a counter to allow the requests to be sequenced. @@ -58,6 +60,28 @@ router.use(function(req, res, next) { // The asterisk (*) means 'ignore anything following this point' // which means we have to be careful about ordering these statements. // + +router.get('/db/getMetadata*', noSQL.w_getMetadata); +router.get('/db/getCapabilities*', noSQL.w_capabilities); +router.get('/db/getBackups*', noSQL.w_getBackups); +router.get('/db/getOne*', noSQL.w_getOne); +router.post('/db/getOne*', noSQL.w_getOne); +router.post('/db/authenticate*', noSQL.w_authenticate); +router.post('/db/listCollections*', noSQL.w_listAllDatabases); +router.post('/db/listDocuments*', noSQL.w_listAllDocuments); +router.post('/db/createBackup*', noSQL.w_createBackup); +router.post('/db/createTable*', noSQL.w_create); +router.post('/db/dropTable*', noSQL.w_drop); +router.post('/db/insert*', noSQL.w_insert); +router.post('/db/update*', noSQL.w_update); +router.post('/db/delete*', noSQL.w_delete); +router.post('/db/buildEntryPage*', noSQL.w_buildEntryPage); +router.post('/db/getDocs*', noSQL.w_getDocs); +router.post('/db/selectMulti*', noSQL.w_selectMulti); +router.post('/db/select2*', noSQL.w_select2); +router.post('/db/select*', noSQL.w_select); +router.post('/db/restoreTable*', noSQL.w_restoreTable); + router.get('/api/getSupportedLanguages*',multi_lingual.languages); router.get('/api/getTextLocations*',multi_lingual.locations); router.post('/api/selectedPrompts*',multi_lingual.prompts); diff --git a/Chapter13/favicon.ico b/Chapter13/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter13/favicon.ico and /dev/null differ diff --git a/Chapter13/index.js b/Chapter13/index.js index dc2ff55..22f9914 100644 --- a/Chapter13/index.js +++ b/Chapter13/index.js @@ -25,6 +25,7 @@ const fs = require('fs'); const mime = require('mime'); const bodyParser = require('body-parser'); const cfenv = require('cfenv'); +const request = require('request'); const cookieParser = require('cookie-parser'); // const session = require('express-session'); @@ -38,6 +39,7 @@ const app = express(); const busboy = require('connect-busboy'); app.use(busboy()); + // the session secret is a text string of arbitrary length which is // used to encode and decode cookies sent between the browser and the server /** @@ -63,6 +65,10 @@ app.use(express.static(__dirname + '/HTML')); app.use(bodyParser.json()); // Define your own router file in controller folder, export the router, add it into the index.js. +if (cfenv.getAppEnv().isLocal == true) +{let protocolToUse = 'http';} +else +{let protocolToUse = 'https';} app.use('/', require('./controller/restapi/router')); @@ -84,7 +90,7 @@ app.locals.wsServer.on('request', function(request) app.locals.connection.on('message', function(message) { let obj ={ime: (new Date()).getTime(),text: message.utf8Data}; // broadcast message to all connected clients - let json = JSON.stringify({ type:'Message', data: obj }); + let json = JSON.stringify({ type:'Message', data: obj.text }); app.locals.processMessages(json); }); @@ -115,6 +121,25 @@ app.locals.processMessages = processMessages; // now set up the http server server.on( 'request', app ); server.listen(appEnv.port, function() {console.log('Listening locally on port %d', server.address().port);}); + +// +// +// +let urlBase = cfenv.getAppEnv(url).url; +console.log('index.js urlBase is: '+urlBase); +// +// execute autoload process to set up initial members and orders in network. +// +let options = {}; +var url = urlBase+'/setup/autoLoad'; +var method = "POST"; +request( { url: url, json: options, method: method }, + function(error, response, body) + { + console.log('index.js autoload (error)', error); + console.log('index.js autoload (body)', body); + }); + /** * load any file requested on the server * @param {express.req} req - the inbound request object from the client diff --git a/Chapter13/network/lib/sample.js b/Chapter13/network/lib/sample.js index 4ce83b2..174b4db 100644 --- a/Chapter13/network/lib/sample.js +++ b/Chapter13/network/lib/sample.js @@ -126,7 +126,7 @@ function OrderFromSupplier(purchase) { * @transaction */ function RequestShipping(purchase) { - if (purchase.order.status == JSON.stringify(orderStatus.Ordered)) + if ((purchase.order.status == JSON.stringify(orderStatus.Ordered)) || (purchase.order.status == JSON.stringify(orderStatus.Backordered))) { purchase.order.shipper = purchase.shipper; purchase.order.requestShipment = new Date().toISOString(); @@ -196,7 +196,6 @@ function RequestPayment(purchase) { {purchase.order.status = JSON.stringify(orderStatus.PayRequest); purchase.order.financeCo = purchase.financeCo; purchase.order.paymentRequested = new Date().toISOString(); - } return getAssetRegistry('org.acme.Z2BTestNetwork.Order') .then(function (assetRegistry) { return assetRegistry.update(purchase.order) @@ -206,6 +205,7 @@ function RequestPayment(purchase) { return (_res); }).catch(function(error){return(error);}); }); + } } /** * Record a payment to the seller @@ -216,7 +216,6 @@ function AuthorizePayment(purchase) { if ((JSON.parse(purchase.order.status).text == orderStatus.PayRequest.text ) || (JSON.parse(purchase.order.status).text == orderStatus.Resolve.text )) {purchase.order.status = JSON.stringify(orderStatus.Authorize); purchase.order.approved = new Date().toISOString(); - } return getAssetRegistry('org.acme.Z2BTestNetwork.Order') .then(function (assetRegistry) { return assetRegistry.update(purchase.order) @@ -226,6 +225,7 @@ function AuthorizePayment(purchase) { return (_res); }).catch(function(error){return(error);}); }); + } } /** * Record a payment to the seller @@ -236,7 +236,6 @@ function Pay(purchase) { if (JSON.parse(purchase.order.status).text == orderStatus.Authorize.text ) {purchase.order.status = JSON.stringify(orderStatus.Paid); purchase.order.paid = new Date().toISOString(); - } return getAssetRegistry('org.acme.Z2BTestNetwork.Order') .then(function (assetRegistry) { return assetRegistry.update(purchase.order) @@ -246,6 +245,7 @@ function Pay(purchase) { return (_res); }).catch(function(error){return(error);}); }); + } } /** * Record a dispute by the buyer diff --git a/Chapter14/favicon.ico b/Chapter14/favicon.ico deleted file mode 100755 index fc9e25d..0000000 Binary files a/Chapter14/favicon.ico and /dev/null differ