import { Component, OnInit, ViewEncapsulation, AfterViewInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import Web3 from 'web3'; import { Helpers } from '../../../../../helpers'; import { ScriptLoaderService } from '../../../../../_services/script-loader.service'; import { DetailsService } from '../../details.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: './create-proposal.component.html', styleUrls: ['./create-proposal.component.css'], encapsulation: ViewEncapsulation.None }) export class CreateProposalComponent implements OnInit, AfterViewInit { public SummerNoteText; public web3; public title: string; public index: Number; loading = false; public userObj; public authMember = false; public message; public category = 0; public categories = []; public categoryName = 'Uncategorized'; public categoryId_name = {}; public categoryId; public categoryData = {}; public selectedCategory = 0; public selectedCid = false; public stakeValue; public minStake; public maxStake; public paramValues = []; public apiParamValues = []; public metamaskLogin = true; public iframeURl = ''; public show = false; constructor( private router: Router, private _script: ScriptLoaderService, private route: ActivatedRoute, private toastr: ToastrService, private details: DetailsService, private globals: GlobalsComponent ) { if (window.location.href.indexOf('iframe') >= 0) { this.iframeURl = '/iframe'; this.show = true; } } public sidebarOpen = false; openSidebar() { this.sidebarOpen = true; } closeSidebar() { this.sidebarOpen = false; } 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'); $('.sidebar-overlay').each(function() { $(this).removeClass('open'); }); } ngOnInit() { let user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); this.authMember = this.userObj.authorized; this.web3 = new Web3(window['web3'].currentProvider); this.web3.eth.defaultAccount = this.web3.eth.coinbase; if (this.web3.eth.accounts[0] == undefined) { this.metamaskLogin = false; } this.indexInitiate(); this.iframeResize(); } indexInitiate() { var urlPath = window.location.href; var index = urlPath.lastIndexOf('/'); var urlCompanyName = urlPath.substring(index + 1, urlPath.length); 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)); let user1 = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user1); console.log(this.userObj); import('../../globals/globals.component').then(module => { module.generator(); }); this.details.setTitle('Create Proposal - ' + this.userObj.companyName); GlobalsComponent.gbmaster.getdAppDetails( this.userObj.companyName, function(error, result) { this.versionNum = result[5].toNumber(); this.companyMasterAddress = result[1]; this.userObj.masterAddress = this.companyMasterAddress; var version; GlobalsComponent.gbmaster.isMemberAuthorized( this.userObj.companyName, this.web3.eth.accounts[0], function(errorMR1, resultMR1) { var authorized = false; if (resultMR1.authorized) { authorized = true; } this.userObj.authorized = authorized; this.authMember = this.userObj.authorized; 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) { 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)); this.getInitialAddress(); clearInterval(timeoutVar1); } }.bind(this), 500 ); }.bind(this) ); }.bind(this) ); } else { import('../../globals/globals.component').then(module => { module.generator(); }); var timeoutVar1 = setInterval( function() { console.log('insideTimeout'); if (this.userObj.companyName in GlobalsComponent.governance) { this.getInitialAddress(); clearInterval(timeoutVar1); } }.bind(this), 500 ); } } Reset() { if (this.datatable != undefined) this.datatable.destroy(); this.mainTableInit(); $('div').removeClass('has-success'); $('div').removeClass('has-danger'); $('#title-error').remove(); $('.summernote').summernote('reset'); this.paramsLength = 0; setTimeout(() => { this.selectedCategory = 0; this.categoryName = 'Uncategorized'; this.iframeResize(); }, 200); } getInitialAddress() { this.initialCalls(); this.details.setdAppName(this.userObj.companyName); this.details.setTitle('Create Proposal - ' + this.userObj.companyName); } public lengthOfCategory; public categoryCount; public decimals = {}; initialCalls() { var category = { id: 0, categoryName: 'Uncategorized', roleName: '', functionValue: 'No' }; this.categoryId_name[0] = 'Uncategorized'; this.categories.push(category); $('.summernote').summernote('code', ''); GlobalsComponent.categoryData[this.userObj.companyName].getCategoryLength( function(errCatLength, resCatLen) { this.lengthOfCategory = resCatLen - 1; this.categoryCount = this.lengthOfCategory; this.getCategoryData(); }.bind(this) ); 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) ); } getCategoryData() { this.getCategoryData1(4); } public roleNameArray; public closingTimeArray; 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; } convertPoolETHtoGBT() { this.router.navigate([ this.iframeURl + '/index/' + this.userObj.companyName ]); $('#categoriesModal').modal('hide'); // $('#buyGBTPool').modal('show'); } public paramsLength = 0; public selectedCategoryData; public incentiveCategory; public purchaseGBTpool = false; public poolGBTbalance; public canCreateProposal; public reason; public authorizedCompany; public tokensToLock; categorySelected() { console.log(this.categoryIdMap[this.selectedCategory]); this.purchaseGBTpool = false; GlobalsComponent.governance[this.userObj.companyName].canCreateProposal( this.web3.eth.accounts[0], this.selectedCategory, function(reason, resCanCreate) { this.canCreateProposal = resCanCreate; this.reason = reason[0]; this.tokensToLock = reason[1]; }.bind(this) ); GlobalsComponent.categoryData[this.userObj.companyName].getSubCategoryData( this.selectedCategory, function(errorSubCatData, resSubCatData) { this.selectedCategoryData = resSubCatData; this.selectedCategoryData.inputType = []; for ( let i = 0; i < this.selectedCategoryData.parameterNames.length; i++ ) { if (this.selectedCategoryData.parameterTypes[i].startsWith('uint')) { this.selectedCategoryData.inputType[i] = 'number'; } else { this.selectedCategoryData.inputType[i] = 'text'; } } this.minStake = this.subCategoryData[this.selectedCategory].minStake; if ( this.parentCategoryData[ this.subCategoryData[this.selectedCategory].categoryId ].mrAllowed[0] == 0 ) { this.authorizedCompany = 'GOVBLOCKS'; } else this.authorizedCompany = this.userObj.companyName; this.incentiveCategory = this.subCategoryData[ this.selectedCategory ].incentives; this.paramsLength = this.selectedCategoryData.parameterNames.length + this.selectedCategoryData.apiParameterNames.length; GlobalsComponent.gbmaster.getPooldAppTokenBalance( this.authorizedCompany, function(error2, result2) { this.iframeResize(); if (result2.e < 10) { this.poolGBTbalance = Math.round(result2 * 100) / 100; } else { this.poolGBTbalance = Math.round((result2 / 1e18) * 100) / 100; } if ( this.incentiveCategory / Math.pow(10, this.decimals[this.authorizedCompany]) > this.poolGBTbalance ) this.purchaseGBTpool = true; }.bind(this) ); }.bind(this) ); // this.selectedCategoryData=this.subCategoryData[this.selectedCategory]; } predicateBy(prop) { return function(a, b) { if (a[prop] > b[prop]) { return 1; } else if (a[prop] < b[prop]) { return -1; } return 0; }; } submitValues(): void { var user = localStorage.getItem('currentUser'); this.userObj = JSON.parse(user); if (this.userObj.email == 'govblocks@govblocks.io') { $('#loginModal').modal('show'); } else { this.SummerNoteText = $('.summernote').summernote('code'); this.details.description = this.SummerNoteText; var isEmpty = $('#summernote').summernote('code'); if (isEmpty != '


' && this.SummerNoteText != '') { this.loading = true; this.details.titleAdded = this.title; var quoteArdetails = [ { id: 0, shortDescription: this.SummerNoteText, title: this.title, description: this.SummerNoteText } ]; if (this.selectedCategory == 0) { var data = { proposalData: quoteArdetails, shortDescription: this.SummerNoteText, votingType: 0 }; GlobalsComponent.governance[this.userObj.companyName].createProposal( data, function(error1, result1) { if (!error1) { this.toastr.info( 'Proposal submitted to ethereum(' + GlobalsComponent.network + '). Awaiting confirmation!' ); this.timeout(result1, 'categorize-proposal'); } else { this.loading = false; } }.bind(this) ); } else { if (this.canCreateProposal) { var categoryIncentive; var categoryDetails; var balance; GlobalsComponent.gbmaster.getPooldAppTokenBalance( this.authorizedCompany, function(error2, result2) { // if (!error2) { balance = balance / Math.pow(10, this.decimals[this.authorizedCompany]); if ( categoryIncentive / Math.pow(10, this.decimals[this.authorizedCompany]) >= balance ) { this.loading = false; $('#buyGBTPool').modal('show'); } else { var optionData = { paramValues: this.paramValues, apiParamValues: this.apiParamValues }; this.selectedCategory = parseInt(this.selectedCategory, 10); var data = { proposalData: quoteArdetails, optionData: optionData, votingType: 0, cId: this.selectedCategory }; GlobalsComponent.governance[ this.userObj.companyName ].createProposalwithOption( data, function(errCreateProp, resCreateProp) { if (!errCreateProp) { this.toastr.info( 'Proposal submitted to ethereum(' + GlobalsComponent.network + '). Awaiting confirmation!' ); this.timeout(resCreateProp, 'proposals'); } else { this.loading = false; } }.bind(this) ); } // } }.bind(this) ); } else { this.loading = false; if (this.reason == 'Not Allowed') this.toastr.warning( 'You are not authorized to create proposal under this category' ); else if (this.reason == 'Less Tokens') this.toastr.warning( 'Lock ' + this.tokensToLock + ' token(s) to create a proposal under this category' ); } } } else { this.toastr.warning('Please enter proposal description'); } } } timeout(hash, urlLink) { setTimeout(() => { console.log('Test'); var boundFunction = GlobalsComponent.gbmaster.getTransactionReceipt( hash, function(error, result) { console.log(error); if (result != null) { setTimeout(() => { this.toastr.success('Proposal Created!'); var proposalId = result.logs[0].topics[2]; proposalId = this.web3.toDecimal(proposalId); this.loading = false; var link; if (urlLink == 'proposals') { link = '/components/' + urlLink + '/' + this.userObj.companyName + '/' + proposalId; } else { link = '/components/' + urlLink + '/' + this.userObj.companyName; } this.router.navigate([this.iframeURl + link]); }, 4000); } else this.timeout(hash, urlLink); }.bind(this) ); }, 10 * 1000); } ngAfterViewInit() { this.createProposalValidation(); $('.summernote').summernote({ placeholder: 'Describe your proposal here. If this proposal has been discussed somewhere before, please mention a reference link.' }); this._script.load( '.m-grid__item.m-grid__item--fluid.m-wrapper', 'assets/demo/default/custom/components/portlets/tools.js', 'assets/demo/default/custom/components/forms/widgets/summernote.js' ); this.iframeResize(); } createProposalValidation = function() { $('#createProposalForm').validate({ rules: { title: { required: true } } }); }; subTableInit(e) { $('
') .attr('id', 'child_data_local_' + e.data.RecordID) .appendTo(e.detailCell) .mDatatable({ data: { type: 'local', source: e.data.Child, paging: false, pageSize: 5, saveState: { cookie: true, webstorage: true } }, pagination: false, language: { infoEmpty: 'No records available - Got it?' }, // layout definition layout: { theme: 'default', scroll: true, height: 300, footer: false, // enable/disable datatable spinner. spinner: { type: 1, theme: 'default' } }, sortable: true, // 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: 80 }, { // width: 80, field: 'stake', title: 'Stake', textAlign: 'center', template: function(row) { return row.stake; } }, { // width: 80, field: 'incentive', title: 'Incentives', textAlign: 'center', template: function(row) { return row.incentive; } } ] }); } public subCategoryData = {}; public childData = {}; public parentCategoryData = {}; public subCategoryCount = 0; public categoryIdMap = {}; 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.categoryIdMap[resSubData.id] = resSubData.categoryId; 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 data = []; getMrSequence(resCatData, i, length, mrData) { if (i == 0) { mrData = ''; } if (resCatData.closingTime[i] != 0) 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) { var interval = setInterval(() => { if ( this.subCategoryCount == Object.keys(this.subCategoryData).length ) { clearInterval(interval); this.mainTableInit(); } }, 100); } else { this.getCategoryData1(cId); } } else if (i < length - 1) { mrData += '=>'; var j = i + 1; this.getMrSequence(resCatData, j, length, mrData); } }.bind(this) ); } public datatable; mainTableInit() { $('#loaderCategoryData').hide(); this.datatable = $('#child_data_local').mDatatable({ // datasource definition data: { type: 'local', source: this.data, pageSize: 10, // display 20 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 Layer', template: function(row) { return row.RoleName; } } ] }); $('#child_data_local').on( 'click', '.rbtn', function(args, err) { console.log(args.currentTarget.attributes.id.value); var i = args.currentTarget.attributes.id.value; this.categoryId = i; this.selectedCid = true; this.categoryName = this.subCategoryData[i].subCategoryName; console.log(this.categoryName); this.selectedCategory = i; console.log(this.selectedCategory); this.paramValues.length = 0; this.stakeValue = null; this.categorySelected(); }.bind(this) ); } iframeResize() { import('../../globals/globals.component').then(module => { module.iframe_resize(); }); } } export class CreateProposalIframeComponent extends CreateProposalComponent {}