import { Component, OnInit, ViewEncapsulation, AfterViewInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Helpers } from '../../../../../helpers'; import Web3 from 'web3'; import { DetailsService } from '../../details.service'; import { ScriptLoaderService } from '../../../../../_services/script-loader.service'; import { ToastrService } from 'ngx-toastr'; import { GlobalsComponent } from '../../globals/globals.component'; declare var $: any; @Component({ selector: '.m-grid__item.m-grid__item--fluid.m-wrapper', templateUrl: './categorize-proposal.component.html', styleUrls: ['./categorize-proposal.component.css'], encapsulation: ViewEncapsulation.None }) export class CategorizeProposalComponent implements OnInit, AfterViewInit { public web3; public startIndex; public lengthOfProposal; public lengthOfCategory; public categoryName; public proposalCount; public proposalIndex; public stakes; public proposals = []; public categories = []; public categoryId; public pindex = 0; public proposalFetchCount = 0; public showProposal = false; public memberAddress; loading = false; public userObj; public gbtPoolBalance; public incentive; public message; public metamaskLogin = true; public iframeURl = ''; constructor( private router: Router, private route: ActivatedRoute, private _script: ScriptLoaderService, private toastr: ToastrService, private detailService: DetailsService, private globals: GlobalsComponent ) { if (window.location.href.indexOf('iframe') >= 0) { this.iframeURl = '/iframe'; } } openSlide(event) { var data_target = event.target.getAttribute('data-target'); $('.sidebar-overlay').each(function() { $(this).removeClass('open'); if ($(this).attr('id') == data_target) { $(this).addClass('open'); } }); } closeSlide(event) { // var data_dismiss = event.target.getAttribute('data-dismiss'); this.categoryId = null; $('.sidebar-overlay').each(function() { $(this).removeClass('open'); }); } ngOnInit() { this.showProposal = false; this.detailService.setTitle('Categorize Proposal'); console.log('Init'); let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); console.log(this.userObj); this.web3 = new Web3(window['web3'].currentProvider); this.web3.eth.defaultAccount = this.web3.eth.coinbase; this.memberAddress = this.web3.eth.accounts[0]; if (this.memberAddress == undefined) { this.memberAddress = '0x0000000000000000000000000000000000000000'; this.metamaskLogin = false; } this.indexInitiate(); } indexInitiate() { var urlPath = window.location.href; var index = urlPath.lastIndexOf('/'); var urlCompanyName = urlPath.substring(index + 1, urlPath.length); console.log(urlCompanyName); if (this.userObj.companyName != urlCompanyName) { var data = { masterAddress: '', userName: this.userObj.userName, companyName: urlCompanyName, GBMasterAddress: this.userObj.GBMasterAddress, allAbis: this.userObj.allAbis, email: this.userObj.email, token: 'token', authorized: true }; localStorage.setItem('currentUser', JSON.stringify(data)); import('../../globals/globals.component').then(module => { module.generator(); }); let user1 = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user1); console.log(this.userObj); GlobalsComponent.gbmaster.getdAppDetails( this.userObj.companyName, function(error, result) { this.versionNum = result[5].toNumber(); this.companyMasterAddress = result[1]; this.userObj.masterAddress = this.companyMasterAddress; GlobalsComponent.gbmaster.getdAppContractAddresses( this.userObj.companyName, function(error2, result2) { if (!error2) { var mrAddress = result2['MemberRoles']; var mrAbi = this.userObj.allAbis[2]; var timeoutVar1 = setInterval( function() { console.log('insideTimeout'); let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); if ( this.userObj.companyName in GlobalsComponent.governance ) { GlobalsComponent.gbmaster.isMemberAuthorized( this.userObj.companyName, this.memberAddress, function(errorMR1, resultMR1) { var authorized = resultMR1.authorized; this.authMember = authorized ? 1 : 0; this.userObj.authorized = authorized; $('#loaderCategorize').hide(); var user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); var data = { masterAddress: this.companyMasterAddress, userName: this.userObj.userName, companyName: urlCompanyName, GBMasterAddress: this.userObj.GBMasterAddress, allAbis: this.userObj.allAbis, email: this.userObj.email, token: 'token', authorized: authorized }; localStorage.setItem( 'currentUser', JSON.stringify(data) ); var user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); this.web3.eth.defaultAccount = this.web3.eth.coinbase; this.memberAddress = this.memberAddress; this.getInitialAddress(); }.bind(this) ); clearInterval(timeoutVar1); } }.bind(this), 500 ); } }.bind(this) ); }.bind(this) ); } else { this.web3.eth.defaultAccount = this.web3.eth.coinbase; this.memberAddress = this.memberAddress; import('../../globals/globals.component').then(module => { module.generator(); }); var timeoutVar1 = setInterval( function() { console.log('insideTimeout'); let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); GlobalsComponent.gbmaster.isMemberAuthorized( this.userObj.companyName, this.memberAddress, function(errorMR1, resultMR1) { this.authMember = resultMR1.authorized ? 1 : 0; }.bind(this) ); $('#loaderCategorize').hide(); if (this.userObj.companyName in GlobalsComponent.governance) { this.getInitialAddress(); clearInterval(timeoutVar1); } }.bind(this), 500 ); } } getInitialAddress() { this.detailService.setdAppName(this.userObj.companyName); this.initialCalls(); } public authMember; public authorizedRole; // checkForAuthorizedMember() { // let ans = GlobalsComponent.governance[this.userObj.companyName].getAuthorizedMemberRoleId(function(errRoleName, resRoleName) { // this.roleId = resRoleName; // GlobalsComponent.memberData[this.userObj.companyName].getRoles_MemberCount(function(errDesc, resDesc) { // this.authorizedRole = resDesc; // GlobalsComponent.gbmaster.isMemberAuthorized(this.userObj.companyName, this.memberAddress, function(errRoleName1, resRoleName1) { // this.memberRoleId = resRoleName1.roleId; // if (this.roleId == this.memberRoleId) { // this.authMember = 1; // $('#loaderCategorize').hide(); // } // else { // this.authMember = 0; // $('#loaderCategorize').hide(); // } // }.bind(this)); // }.bind(this)); // }.bind(this)); // } public decimals = {}; public authorizedCompany; initialCalls() { console.log('Initializing ipfs'); // this.checkForAuthorizedMember(); this.checkGBTPoolBalance('GOVBLOCKS'); this.checkGBTPoolBalance(this.userObj.companyName); this.startIndex = 0; this.getProposalLength(); this.getCategoriesLength(); GlobalsComponent.gbmaster.getdAppTokenDecimals( 'GOVBLOCKS', function(errGBTdecimals, resGBTdecimals) { this.decimals['GOVBLOCKS'] = resGBTdecimals; }.bind(this) ); GlobalsComponent.gbmaster.getdAppTokenDecimals( this.userObj.companyName, function(errTokendecimals, resTokendecimals) { this.decimals[this.userObj.companyName] = resTokendecimals; }.bind(this) ); } public GBTBalance = {}; checkGBTPoolBalance(dAppName) { console.log('Entered'); let pBalance = GlobalsComponent.gbmaster.getPooldAppTokenBalance( this.userObj.companyName, function(errPoolBal, resPoolBal) { this.GBTBalance[dAppName] = resPoolBal.toNumber() / Math.pow(10, this.decimals[this.authorizedCompany]); }.bind(this) ); } predicateBy(prop) { return function(a, b) { if (a[prop] > b[prop]) { return 1; } else if (a[prop] < b[prop]) { return -1; } return 0; }; } selectProposal(index) { this.enableFormField = false; if (this.datatable != undefined && this.datatable != '') { this.datatable.destroy(); } var user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); if (this.userObj.email == 'govblocks@govblocks.io') { this.message = 'Please login to your google account in order to categorize proposal
'; $('#loginModal').modal('show'); } else { // $('#m_modal_6').modal('show'); this.pindex = index; this.mainTableInit(); } } convertPoolETHtoGBT() { this.router.navigate([ this.iframeURl + 'index/' + this.userObj.companyName ]); $('#m_modal_6').modal('hide'); // $('#buyGBTPool').modal('show'); } getProposalLength() { GlobalsComponent.proposalData[this.userObj.companyName].getProposalLength( function(error2, resultlength) { if (!error2) { this.lengthOfProposal = resultlength; var i: number; this.proposals = []; var count = 0; this.proposalCount = this.lengthOfProposal - 1; if (this.lengthOfProposal == 1) { $('#loader').hide(); this.showProposal = true; } for (i = this.startIndex + 1; i < this.lengthOfProposal; i++) { let proposal: any = {}; count++; this.getProposalDetailsById3(i, proposal); // if(count==this.lengthOfProposal){ // if(this.proposals.length==0){ // // this.showProposal=true; // } // } } } else { console.log('Here in error of length'); } }.bind(this) ); } public categoryCount; getCategoriesLength() { let cat_length = GlobalsComponent.categoryData[ this.userObj.companyName ].getCategoryLength( function(_error2, _resultlength) { if (!_error2) { this.lengthOfCategory = _resultlength - 1; var i: number; this.catId = 4; // Getting category index by hiding Initial categories. this.categoryCount = this.lengthOfCategory - 0; this.getCategoryData1(this.catId); } else { console.log('Here in error of length'); } }.bind(this) ); } ngAfterViewInit() { this.formCategorize(); } getProposalDetailsById3(i, proposal) { let ans = GlobalsComponent.proposalData[ this.userObj.companyName ].getProposalDetails( i, function(errorId3, resultOfgetProposal) { if (!errorId3) { this.totalSolutions = resultOfgetProposal[4].toNumber(); proposal.index = resultOfgetProposal[0].toNumber(); proposal.categoryId = resultOfgetProposal[2].toNumber(); proposal.proposalStatusIndex = resultOfgetProposal[3].toNumber(); let totVotes = GlobalsComponent.proposalData[ this.userObj.companyName ].getAllVoteIdsLength_byProposal( i, function(errorTotalVotes, resultTotalVotes) { proposal.totalVotes = resultTotalVotes; let proData = GlobalsComponent.proposalData[ this.userObj.companyName ].getProposalEventData( i, function(errorProposalData, resultProposalData) { proposal.title = resultProposalData.proposalTitle; proposal.description = resultProposalData.proposalSD; // if(resultProposalData=="") // { // proposal.description=""; // } // else if(proposal.categoryId == 3 || proposal.categoryId == 4) // { // proposal.description = resultProposalData.proposalDescHash.description; //returns description of proposal // } // else // { // var html = ""+resultProposalData.proposalDescHash.description+""; // var div = document.createElement("div"); // div.innerHTML = html; // proposal.description = div.innerText; // } proposal.totalOptions = resultOfgetProposal.totalSolutions; proposal.status = resultOfgetProposal[1]; var d = new Date(resultProposalData.dateAdd * 1000); var options = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; proposal.dateAdded = d.toLocaleDateString('en', options); let ans = GlobalsComponent.categoryData[ this.userObj.companyName ].getSubCategoryName( proposal.categoryId, function(errorCategory, resultCategory) { if (!errorCategory) { proposal.categoryName = resultCategory; if (proposal.categoryId == 0) { $('#loader').hide(); this.proposals.push(proposal); } this.proposalFetchCount++; if (this.proposalFetchCount == this.proposalCount) { this.proposals.sort(this.predicateBy('index')); $('#loader').hide(); if (this.proposals.length <= 0) { this.showProposal = true; } } $('#loader').hide(); } else { console.log( 'Error of getCategoryName function: ' + errorCategory ); } }.bind(this) ); }.bind(this) ); }.bind(this) ); } else { console.log('Here in error of getProposalDetailsById3'); console.log(errorId3); } }.bind(this) ); } getDataFromHash(hash) { if (hash == '') { return hash; } else { console.log(hash); var XMLHttp = new XMLHttpRequest(); XMLHttp.open('GET', 'https://ipfs.govblocks.io/ipfs/' + hash, false); XMLHttp.send(null); // // // this gives the json containing the details - title, description, voting type var hashDetails = JSON.parse(XMLHttp.responseText); console.log(hashDetails); return hashDetails; } } selectCategory(i) { // $('tr').click(function() { // $(this).find('input:radio').prop('checked', true); // }) this.categoryId = i; this.categoryId = parseInt(this.categoryId, 10); // this.categoryName=this.childData[i].CategoryName; this.categoryName = this.subCategoryData[i].subCategoryName; } change_seconds_to_hours(d) { var h = Math.floor(d / 3600); d %= 3600; var minutes = Math.floor(d / 60); var time; if (h < 1) { time = minutes + ' min'; } else { if (minutes < 1) { if (h > 1) time = h + ' hours'; else time = h + ' hour'; } else time = h + ' h ' + minutes + ' min'; } return time; } getCategoryData1(categoryId) { this.childData[categoryId] = []; GlobalsComponent.categoryData[ this.userObj.companyName ].getParentCategoriesData( categoryId, function(errorCatData, resCatData) { GlobalsComponent.categoryData[ this.userObj.companyName ].getSubCategoryIdsFromParent( resCatData.categoryId, function(errorSubIds, resSubIds) { this.subCategoryCount += resSubIds.length; for (let i = 0; i < resSubIds.length; i++) { GlobalsComponent.categoryData[ this.userObj.companyName ].getSubCategoryData1( resSubIds[i], function(errSubData, resSubData) { if ( this.parentCategoryData[resSubData.categoryId] .mrAllowed[0] == 0 ) { this.authorizedCompany = 'GOVBLOCKS'; } else this.authorizedCompany = this.userObj.companyName; this.childData[resSubData.categoryId].push(resSubData); var value = '\ \
' + resSubData.minStake / Math.pow(10, this.decimals[this.authorizedCompany]) + '
Minimum
'; resSubData.stake = value; resSubData.incentive = '\ \
' + resSubData.incentives / Math.pow(10, this.decimals[this.authorizedCompany]) + '
'; this.subCategoryData[resSubData.id] = resSubData; }.bind(this) ); } }.bind(this) ); var mrSequence = resCatData.mrSequence; this.parentCategoryData[resCatData.categoryId] = resCatData; this.getMrSequence(resCatData, 0, resCatData.mrSequence.length, ''); }.bind(this) ); } public subCategoryData = {}; public childData = {}; public parentCategoryData = {}; public data = []; public buttonDisabled = true; getMrSequence(resCatData, i, length, mrData) { if (i == 0) { mrData = ''; } try { var closingTime = this.change_seconds_to_hours( resCatData.closingTime[i].toNumber() ); } catch (err) { closingTime = resCatData.closingTime[i]; } resCatData.closingTime[i] = closingTime; GlobalsComponent.memberData[this.userObj.companyName].getMemberRoleNameById( resCatData.mrSequence[i].toNumber(), function(errorMRname, resultMRname) { var roleName = resultMRname; mrData += ''; if (i == length - 1) { mrData += '
' + roleName + '
' + resCatData.majorityVote[i].toNumber() + '% in ' + resCatData.closingTime[i] + '
'; var data = { id: resCatData.categoryId, CategoryHead: resCatData.categoryName, RoleName: mrData, Child: this.childData[resCatData.categoryId] }; this.data.push(data); var cId = resCatData.categoryId + 1; if (resCatData.categoryId == this.lengthOfCategory) { this.mainTableInit(); this.buttonDisabled = false; } else { this.getCategoryData1(cId); } } else if (i < length - 1) { mrData += '=>'; var j = i + 1; this.getMrSequence(resCatData, j, length, mrData); } }.bind(this) ); } public purchaseGBTpool; Reset() { $('div').removeClass('has-success'); $('div').removeClass('has-danger'); $('.form-control-feedback').remove(); } hex_to_ascii(str1) { var hex = str1.toString(); var str = ''; for (var n = 0; n < hex.length; n += 2) { str += String.fromCharCode(parseInt(hex.substr(n, 2), 16)); } str1 = ''; for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) != 0) { str1 += str[i]; } } return str1; } timeout(hash) { setTimeout(() => { console.log('Test'); var boundFunction = this.web3.eth.getTransactionReceipt( hash, function(error, result) { console.log(error); console.log(result); if (result != null) { setTimeout(() => { this.toastr.success('Categorization Successfull!'); this.loading = false; this.initialCalls(); $('#m_modal_6').modal('hide'); this.router.navigate([ this.iframeURl + '/components/proposals/' + this.userObj.companyName + '/' + this.pindex + '' ]); }, 4000); } else { this.timeout(hash); } }.bind(this) ); }, 10 * 1000); } public incenTransFails = false; callcategorizeProposal(details) { let ans = GlobalsComponent.governance[ this.userObj.companyName ].categorizeProposal( details, function(error1, result1) { if (!error1) { console.log('here is the result categorizeProposal' + result1); this.toastr.info( 'Request submitted to ethereum(' + GlobalsComponent.network + '). Awaiting confirmation!' ); this.timeout(result1); } else { console.log('Here in error of categorizeProposal'); this.loading = false; console.log(error1); } }.bind(this) ); } public hasEnoughPoolBalance = true; submit(pindex): void { this.loading = true; var details = { proposalId: pindex, categoryId: this.categoryId, proposalComplexityLevel: 0 }; if ( this.parentCategoryData[this.subCategoryData[this.categoryId].categoryId] .mrAllowed[0] == 0 ) { this.authorizedCompany = 'GOVBLOCKS'; } else { this.authorizedCompany = this.userObj.companyName; } GlobalsComponent.gbmaster.getPooldAppTokenBalance( this.authorizedCompany, function(errPoolBal, resPoolBal) { // if (!errPoolBal) { this.gbtPoolBalance = resPoolBal.toNumber() / Math.pow(10, this.decimals[this.authorizedCompany]); if ( this.subCategoryData[this.categoryId].incentives / Math.pow(10, this.decimals[this.authorizedCompany]) == 0 || this.subCategoryData[this.categoryId].incentives / Math.pow(10, this.decimals[this.authorizedCompany]) <= this.gbtPoolBalance ) { this.hasEnoughPoolBalance = true; this.callcategorizeProposal(details); } else { this.hasEnoughPoolBalance = false; this.incenTransFails = true; this.toastr.error( this.userObj.companyName + ' dont have enough Pool Balance!' ); this.loading = false; } // } // else { // console.log("Error in getting pool balance"); // this.loading = false; // } }.bind(this) ); } formCategorize() { $('#validCategorize').validate({ rules: { incentiveValue: { required: true } } }); } removeCondition() { this.incenTransFails = false; } // Child Table subTableInit(e) { $('
') .attr('id', 'child_data_local1_' + e.data.RecordID) .appendTo(e.detailCell) .mDatatable({ data: { type: 'local', source: e.data.Child, pageSize: 10, saveState: { cookie: true, webstorage: true } }, // layout definition layout: { theme: 'default', scroll: true, height: 300, footer: false, // enable/disable datatable spinner. spinner: { type: 1, theme: 'default' } }, sortable: false, pagination: false, // columns definition columns: [ { field: 'id', title: '', width: 15, sortable: false, template: function(row) { return ( '' ); } }, { field: 'subCategoryName', title: 'Category Name' }, { field: 'automaticAction', title: 'Automatic Action' }, { // width: 200, field: 'stake', title: 'Stake', textAlign: 'center', template: function(row) { return row.stake; } }, { // width: 200, field: 'incentive', title: 'Incentives', textAlign: 'center', template: function(row) { return row.incentive; } } ] }); } public enableFormField = false; public datatable; mainTableInit() { var value = '\ \
1
Min
5
Max
'; var roleName = '\ \
Advisory Board
60%
in 30 min
=>Members
50%
in 30 min
'; var data = [ { id: 1, CategoryHead: 'Member Management', RoleName: roleName, stake: value, Child: [{ CategoryName: 'Cat 1', AutomaticAction: 'Yes' }] } ]; this.datatable = $('#child_data_local1').mDatatable({ // datasource definition data: { type: 'local', source: this.data, pageSize: 10, // display 10 records per page saveState: { cookie: true, webstorage: true } }, // layout definition layout: { theme: 'default', scroll: false, height: null, footer: false }, sortable: false, filterable: false, pagination: false, detail: { title: 'View Sub categories', content: this.subTableInit }, search: { input: $('#generalSearch') }, // columns definition columns: [ { field: 'id', title: '', width: 10 }, { width: 250, field: 'CategoryHead', title: 'Category Head' }, { width: 250, field: 'RoleName', title: 'Voting Layers', template: function(row) { return row.RoleName; } } ] }); $('#child_data_local1').on( 'click', '.rbtn', function(args, err) { console.log(args.currentTarget.attributes.id.value); var i = parseInt(args.currentTarget.attributes.id.value); var cId = i; this.enableFormField = true; this.incentive = null; this.selectCategory(i); }.bind(this) ); } } export class CategorizeProposalIframeComponent extends CategorizeProposalComponent {}